java - 如何在 "looking"明显表明测试通过的情况下编写单元测试?

标签 java unit-testing

有时,我会遇到这样的情况,我需要测试的只是程序是否执行到某个点而没有抛出任何异常或者程序被中断或陷入无限循环等等。

我不明白的是如何为此编写单元测试。

例如,考虑下面的“单元测试”——

@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/

相关文章:

java - 消息驱动的 Bean 选择器 (JMS)

java - 无锁并发栈实现

java - Solr:得分完全匹配高于部分匹配

c - 如何编写具有多个源文件和头文件的检查测试 makefile.am?

typescript - Jest/ Jasmine : Weird Execution Order Of beforeEach()

java - Runtime.getRuntime().exec(String[]) 安全

java - 迭代所有不为空的槽,二维数组?

java - 如何使用PowerMock模拟除被测类之外的另一个类的私有(private)方法?

selenium - 针对跨多个浏览器的 Selenium 测试的自动化测试套件包结构的建议

javascript - 测试时将 Meteor.userId 传递给经过验证的方法