问题

在JUnit测试用例中实际使用'fail'是什么?


#1 热门回答(106 赞)

我发现它有用的一些情况:

  • 标记一个不完整的测试,因此它会失败并在你完成之前发出警告
  • 确保抛出异常:

尝试{
  // 做东西...
  失败("不抛出异常");
} catch(例外e){
  assertTrue(e.hasSomeFlag());
}

注意:

从JUnit4开始,有一种更优雅的方法来测试抛出异常:使用注释@Test(expected=IndexOutOfBoundsException.class)

但是,如果你还想检查异常,那么这将无效,那么你仍然需要fail()


#2 热门回答(9 赞)

假设你正在为-ve流编写测试用例,其中被测试的代码应引发异常

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}

#3 热门回答(6 赞)

我认为通常的用例是在负面测试中没有抛出异常时调用它。

像下面的伪代码:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

原文链接