有时,我遇到的情况是我需要测试的是程序的执行是否达到某个点而没有抛出任何异常,或者程序被中断或陷入无限循环或某事.
我不明白的是如何为此编写单元测试.
例如,考虑以下"单元测试" -
@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.
}
Run Code Online (Sandbox Code Playgroud)
通常,在测试结束时,我有一个声明如下 -
assertEquals(expectedString, actualString);
Run Code Online (Sandbox Code Playgroud)
但是如何为上述情况编写assertEquals或其他类型的测试语句?
您的代码看起来很好,只需删除注释,但请保留以下内容:
// If execution reaches this point, that means the program ran successfully.
Run Code Online (Sandbox Code Playgroud)
因此,您的代码读者将理解为什么没有断言.
值得注意的是,在您的测试中调用的每个方法都应该具有某种效果,即使您说"您不关心",该效果也应该被认为是正确发生的.
如果你坚持不需要检查,添加一个注释来解释原因 - 这将节省读者浏览你的代码,找出为什么"它无关紧要",例如:
// No assertions have been made here because the state is unpredictable.
// Any problems with execution will be detected during integration tests.
Run Code Online (Sandbox Code Playgroud)