如何使用JUNIT和Mockito测试这个方法?

huangapple go评论79阅读模式
英文:

How should I test this method with JUNIT and Mockito

问题

I'm new to Junit and Mockito unit testing. I need to unit test the method "processFiles(final File folder)".

When I run the test I get a NullPointerException at "if (!this.studentService.isFileOk(data))".

Can you help me to how I should be testing this method properly. Thanks a lot in advance.

This is a part of the code from the processFiles method:

@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();
        }
    }
}

And this is how I'm trying to test my processFile method


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());

    }
英文:

I'm new to Junit and Mockito unit testing. I need to unit test the method "processFiles(final File folder)"

When I run the test I get a NullPointerException at "if (!this.studentService.isFileOk(data))".

Can you help me to how I should be testing this method properly. Thanks a lot in advance.

This is a part of the code from the processFiles method:

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

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

And this is how I'm trying to test my processFile method

 

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(&quot;tempFile.txt&quot;);
        final File tempFile2 = temporaryFolder.newFile(&quot;tempFile2.txt&quot;);

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


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


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


        listFilesService.processFiles(temporaryFolder.getRoot());

    }

答案1

得分: 1

您正在手动创建ListFilesService对象,而不让Mockito注入模拟对象(具体来说是studentService):

listFilesService = new ListFilesService();

这样创建对象时,studentService字段保持为null,因为它没有以任何方式进行初始化,这会导致应用程序出现NullPointerException

您可能想要像这样开始您的测试类:

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

然后调用MockitoAnnotations.initMocks(this)(更多信息请参阅此处)。

模拟对象的初始化应在测试运行之前完成,所以最好使用带有@Before注解的设置方法(更多信息请参阅此处)。

记得在测试中使用listFilesService字段,而不要使用new来创建对象!

英文:

You're creating the ListFilesService object by hand, not letting Mockito inject the mocks (specifically - studentService):

listFilesService = new ListFilesService();

When creating the object like this, the field studentService remains null, because it is not initialized in any way and it causes the application to fail with NullPointerException.

What you probably want to do is start your test class like this:

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

and then call MockitoAnnotations.initMocks(this) (read more here).

Mocks initialization should be done before the test runs, so it's best to use a set up method with @Before annotation (read more here).

Remember to use the listFilesService field in your test and not create the object by new!

huangapple
  • 本文由 发表于 2020年8月4日 17:29:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63243937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定