簡體   English   中英

我應該如何使用 JUNIT 和 Mockito 測試此方法

[英]How should I test this method with JUNIT and Mockito

我是 Junit 和 Mockito 單元測試的新手。 我需要對方法“processFiles(最終文件夾)”進行單元測試

當我運行測試時,我在“if (.this.studentService.isFileOk(data))”處得到一個 NullPointerException。

你能幫我看看我應該如何正確測試這個方法。 提前非常感謝。

這是 processFiles 方法的部分代碼:

@Stateless
public class ListFilesService{
 
  @EJB
  private transient StudentService studentService;
 
 public void processFiles(final File folder)
    {
        File[] fileNames = folder.listFiles();
        List<String> lines = new ArrayList<>();
        
        try
        {
                    List<String> l = readContent(file);
                    l.forEach(i -> lines.add(i));

            String[] data = lines.get(0).trim().split(";");
            if (!this.studentService.isFileOk(data))
            {
                LOG.warning(String.format("File not valid"));
            }
            else
            {
                studentService.storeStudents(lines);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

這就是我試圖測試我的 processFile 方法的方式

 

public class TestCases
{
 
 
    @Mock
    ListFilesService listFilesService;
    
    @Mock
    public StudentService studentService;

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();
 
 
 @Test
    public void testWrite2() throws IOException
    {

        final File tempFile1 = temporaryFolder.newFile("tempFile.txt");
        final File tempFile2 = temporaryFolder.newFile("tempFile2.txt");

        String[] data = {"LastName", "FirstName", "Age"};


        listFilesService = new ListFilesService();
        studentService = Mockito.mock(StudentService.class);
        when(studentService.isFileOk(eq(data))).thenReturn(true);


        FileUtils.writeStringToFile(tempFile1, "LastName;FirstName;Age" +
                "\nxxx1;nnnn1;15", "UTF-8");
        FileUtils.writeStringToFile(tempFile2, "LastName;FirstName;Age" +
                "\nxxx2;nnnn2;19", "UTF-8");


        listFilesService.processFiles(temporaryFolder.getRoot());

    }

您正在手動創建ListFilesService object ,而不是讓 Mockito 注入模擬(特別是 - studentService ):

listFilesService = new ListFilesService();

當像這樣創建 object 時,字段studentService仍然是 null,因為它沒有以任何方式初始化,它會導致應用程序失敗並出現NullPointerException

您可能想要做的是像這樣開始您的測試 class :

@Mock
private StudentService studentService;
@InjectMocks
private ListFilesService listFilesService;

然后調用MockitoAnnotations.initMocks(this)在這里閱讀更多)。

模擬初始化應該在測試運行之前完成,所以最好使用帶有@Before注釋的設置方法(在這里閱讀更多)。

請記住在您的測試中使用listFilesService字段,而不是通過new創建 object!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM