有时,我会遇到这样的情况,我需要测试的只是程序是否执行到某个点而没有抛出任何异常或者程序被中断或陷入无限循环等等。
我不明白的是如何为此编写单元测试。
例如,考虑下面的“单元测试”——
@Test
public void testProgramExecution()
{
Program program = new Program();
program.executeStep1();
program.executeStep2();
program.executeStep3();
// if execution reaches this point, that means the program ran successfully.
// But what is the best practice?
// If I leave it like this, the test will "pass",
// but I am not sure if this is good practice.
}
通常,在测试结束时,我会有这样的陈述-
assertEquals(expectedString, actualString);
但是如何为上述情况编写 assertEquals 或其他类型的测试语句?
最佳答案
您的代码看起来不错,只需删除注释,但留下这个:
// If execution reaches this point, that means the program ran successfully.
这样您的代码的读者就会理解为什么没有断言。
值得注意的是,测试中调用的每个方法都应该有某种效果,并且应该断言该效果正确发生,即使您说“您不关心”也是如此。
如果您坚持不需要检查,请添加注释来解释原因 - 这将使读者免于翻阅您的代码以自行找出“无关紧要”的原因,例如:
// No assertions have been made here because the state is unpredictable.
// Any problems with execution will be detected during integration tests.
关于java - 如何在 "looking"明显表明测试通过的情况下编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058763/