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

San*_*nju 112 java junit unit-testing junit4

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

sle*_*ske 128

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

  • 标记一个不完整的测试,因此它会失败并在您完成之前发出警告
  • 确保抛出异常:
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}
Run Code Online (Sandbox Code Playgroud)

注意:

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

但是,如果您还想检查异常,那么这将不起作用,那么您仍然需要fail().

  • 请看一篇关于失败与预期注释的相对优点的博客文章:http://blog.jooq.org/2016/01/20/use-junits-expected-exceptions-sparingly/ (3认同)
  • @sleske"如果你还想检查异常,那么你仍然需要失败()" - 不.ExpectedException就是这样,请参阅https://github.com/junit-team/junit4/wiki/exception-testing (3认同)

kar*_*eek 11

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

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


phi*_*ant 8

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

像下面的伪代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果不检查catch块中的某些内容,可以使用@ExpectedException(NullNullPointerException.class)方法批注来声明您期望异常(特殊类型). (3认同)

Rya*_*n D 7

我已经在我的@Before方法中出现问题的情况下使用过它.

public Object obj;

@Before
public void setUp() {
    // Do some set up
    obj = new Object();
}

@Test
public void testObjectManipulation() {
    if(obj == null) {
        fail("obj should not be null");
     }

    // Do some other valuable testing
}
Run Code Online (Sandbox Code Playgroud)