最佳实践:fail()vs assertTrue(false)

Tre*_*iss 14 java testing junit

当故意使测试用例失败时(例如,当没有抛出异常时)我看到人们同时使用fail()和assertTrue(false).使用其中一个有什么好处吗?

try {
    //method call that should throw exception
    fail("oops");
} catch (Exception e) {}
Run Code Online (Sandbox Code Playgroud)

try {
    //method call that should throw exception
    assertTrue("oops", false);
} catch (Exception e) {}
Run Code Online (Sandbox Code Playgroud)

Kep*_*pil 21

使用其中一个有什么好处吗?

功能上,没有.但是,fail()更清楚地传达意图,因此更好.


BeR*_*ive 13

expected@Test注释中使用JUnit的参数

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
    int i = 1/0;
}  
Run Code Online (Sandbox Code Playgroud)

如果ArithmeticException没有抛出,这将失败.

  • 我发现`EpectedException`规则是一种更强大的机制,用于测试预期的异常,因为它可以放在测试方法之前,从而确保它不是引发异常的测试设置. (3认同)
  • OP确实说"例如,当没有抛出异常时"可能还有其他情况. (2认同)

Pet*_*rey 5

assertTrue只是调用失败.

恕我直言失败()更简单,更清晰.