unit-testing - 单元测试是否必须有像 "assertEquals(..)"这样的断言

标签 unit-testing junit

我有一个小的 JUnit 测试,可以将对象导出到文件系统。首先,我的测试看起来像这样

public void exportTest {
   //...creating a list with some objects to export...    
   JAXBService service = new JAXBService();
   service.exportList(list, "output.xml");
}

通常我的测试包含一个像 assertEquals(...) 这样的断言。所以我把代码改成如下

public void exportCustomerListTest() throws Exception {
    // delete the old resulting file, so we can test for a new one at the end
    File file = new File("output.xml");
    file.delete();

    //...creating a list with some objects to export...

    JAXBService service = new JAXBService();
    service.exportCustomers(list, "output.xml");

    // Test if a file has been created and if it contains some bytes
    FileReader fis = new FileReader("output.xml");
    int firstByte = fis.read();

    assertTrue(firstByte != -1 );
}

我需要这个吗?还是第一种方法就足够了?我问是因为,第一种方法实际上只是“测试”代码运行,而不是测试任何结果。或者我是否可以依赖“契约(Contract)”,即如果导出方法无一异常(exception)地运行测试通过?

谢谢

最佳答案

好吧,您正在测试您的代码是否运行完成而没有任何异常 - 但您没有测试任何关于输出的内容。

为什么不保留一个包含预期输出的文件,并将其与实际输出进行比较?请注意,如果你有一个 expertCustomers 的重载需要一个 Writer - 那么你可以传入一个 StringWriter 并且只写到内存中。您可以通过多种方式对其进行测试,只需对采用文件名的重载进行一次测试,因为这只会创建一个包裹在 OutputStreamWriter 中的 FileOutputStream,然后调用更彻底的测试方法。您可能真的只需要检查是否存在正确的文件。

关于unit-testing - 单元测试是否必须有像 "assertEquals(..)"这样的断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1596375/

相关文章:

unit-testing - 使用mockito模拟HttpClient请求

java - 如何让 Spring 使用多个上下文 Autowiring 集成测试类?

linux - 如何使用unix在数据库中登录和执行命令?

c# - 如何在编写单元测试时访问方法的局部变量

python - 如何在 Spyder IDE 中运行和调试单元测试

java - Easymock:匹配器调用的使用超出预期

javascript - 如何测试 Angular 中嵌入的内容?

c# - 如何在 Visual Studio 11 Dev Preview 中使用 MSTEST?

java - 在 JUnit 测试中处理 Swing 事件

java - Spring MVC : Testing particular annotated method gets invoked