简体   繁体   English

CSV阅读器的模拟和单元测试

[英]mockito and unit test for a csv reader

Does it make sense to mock in unit test of a csv reader where we want to read the csv and put them into POJOs and make some queries? 在要读取csv并将其放入POJO并进行一些查询的csv阅读器的单元测试中进行模拟是否有意义? (specifically I mean mocking file read). (特别是我的意思是模拟文件读取)。

Let's assume the following example: 让我们假设以下示例:

 ICsvBeanReader beanReader = null;
    beanReader = new CsvBeanReader(new FileReader(csvFileName),
            CsvPreference.STANDARD_PREFERENCE);
    String[] header = beanReader.getHeader(true);
    Book bookBean = null;
    while ((bookBean = beanReader.read(Book.class, header,
         processors))!= null) {
     books.add(bookBean);
    }

Thank you in advance. 先感谢您。

This seems like a good idea - it can decouple your unit being tested from your implementation of read(). 这似乎是一个好主意-它可以将要测试的单元与read()的实现分离。 That way if you change to a different library to read the files, your unit tests don't all have to be rewritten. 这样,如果您更改为其他库以读取文件,则不必全部重写单元测试。

Strictly speaking, a unit test is designed to test the functionality of a piece of code, rather than the integration of code with an external part of the program. 严格来说,单元测试旨在测试一段代码的功能,而不是测试代码与程序外部的集成。 Testing the functionality of reading an actual file would be an integration test, rather than a unit test. 测试读取实际文件的功能将是集成测试,而不是单元测试。 An integration test is important too, because you want to make sure that your file reader can function on actual files. 集成测试也很重要,因为您要确保文件阅读器可以在实际文件上运行。 But for the purpose of ensuring that the code runs, you can also create a unit test. 但是,为了确保代码能够运行,您还可以创建一个单元测试。

To create a unit test, you can mock the file reader object to return a dummy response ( byte[] or whatever type the interface provides). 要创建单元测试,可以模拟文件读取器对象以返回虚拟响应( byte[]或接口提供的任何类型)。 Then you can populate your POJOs and do your assertions that everything behaves as expected. 然后,您可以填充POJO并声明所有行为均符合预期。

So to summarize, both an integration test and a unit test might be a good idea, but a unit test will allow you to isolate and test the logic of your code. 因此,总而言之,集成测试和单元测试都可能是一个好主意,但是单元测试将使您能够隔离和测试代码的逻辑。

Update: 更新:

To take your updated code sample into account, I would go about mocking the CsvBeanReader like this: 为了考虑到更新的代码示例,我将像这样CsvBeanReader

ICsvBeanReader mockedBeanReader = mock(CsvBeanReader.class);
Book book1 = new Book();
Book book2 = new Book();
Book book3 = new Book();
when(mockedBeanReader.getHeader(true))
    .thenReturn(new String[]{"here", "is", "header"});
when(mockedBeanReader.read(Book.class, header, processors))
    .thenReturn(book1)
    .thenReturn(book2)
    .thenReturn(book3);

And now you have a fully mocked CsvBeanReader object. 现在,您有了一个完全CsvBeanReader对象。 You can perform assertions on your POJOs and verify that the business logic of your code be correct. 您可以在POJO上执行断言,并验证代码的业务逻辑是否正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM