Java JUnit 测试用例中“失败”的实际用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3869954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:08:12  来源:igfitidea点击:

What's the actual use of 'fail' in JUnit test case?

javaunit-testingjunitjunit4

提问by Sanju

What's the actual use of 'fail' in JUnit test case?

JUnit 测试用例中“失败”的实际用途是什么?

采纳答案by sleske

Some cases where I have found it useful:

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

  • mark a test that is incomplete, so it fails and warns you until you can finish it
  • making sure an exception is thrown:
  • 标记一个未完成的测试,因此它会失败并警告您直到您可以完成它
  • 确保抛出异常:
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}

Note:

笔记:

Since JUnit4, there is a more elegant way to test that an exception is being thrown: Use the annotation @Test(expected=IndexOutOfBoundsException.class)

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

However, this won't work if you also want to inspect the exception, then you still need fail().

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

回答by philant

I think the usual use case is to call it when no exception was thrown in a negative test.

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

Something like the following pseudo-code:

类似于以下伪代码:

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
    }
}

回答by kartheek

lets say you are writing a test case for a -ve flow where the code being tested should raise an exception

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

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

回答by user3044364

This is how I use the Fail method.

这就是我使用 Fail 方法的方式。

There are three states that your test case can end up in

您的测试用例可能会处于三种状态

  1. Passed : The function under test executed successfully and returned data as expected
  2. Not Passed : The function under test executed successfully but the returned data was not as expected
  3. Failed : The function did not execute successfully and this was not
  1. Passed :被测函数执行成功并按预期返回数据
  2. Not Passed : 被测函数执行成功但返回数据不符合预期
  3. 失败:函数没有成功执行,这不是

intended (Unlike negative test cases that expect a exception to occur).

预期(与期望发生异常的负面测试用例不同)。

If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.

如果您使用的是 eclipse,则三个状态分别由绿色、蓝色和红色标记指示。

I use the fail operation for the the third scenario.

我在第三个场景中使用失败操作。

e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}

例如:public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}

  1. Passed Case : a = new Interger(1), b= new Integer(2) and the function returned 3
  2. Not Passed Case: a = new Interger(1), b= new Integer(2) and the function returned soem value other than 3
  3. Failed Case : a =null , b= null and the function throws a NullPointerException
  1. 通过案例:a = new Interger(1), b= new Integer(2) 并且函数返回 3
  2. 未通过案例:a = new Interger(1), b= new Integer(2) 并且函数返回的 soem 值不是 3
  3. 失败案例: a =null , b= null 并且函数抛出 NullPointerException

回答by Ryan D

I've used it in the case where something may have gone awry in my @Before method.

我在 @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
}

回答by Alen Siljak

I, for example, use fail()to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

例如,我fail()用来表示尚未完成的测试(它发生了);否则,他们将显示为成功。

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

这可能是因为我不知道 NUnit 中存在某种不完整的() 功能。

回答by Udo Held

The most important use case is probably exception checking.

最重要的用例可能是异常检查。

While junit4 includes the expected elementfor checking if an exception occurred, it seems like it isn't part of the newer junit5. Another advantage of using fail()over the expectedis that you can combine it with finallyallowing test-case cleanup.

虽然 junit4 包含用于检查是否发生异常的预期元素,但它似乎不是较新的 junit5 的一部分。使用的另一个优点fail()expected是,你可以结合它finally允许测试用例清理。

dao.insert(obj);
try {
  dao.insert(obj);
  fail("No DuplicateKeyException thrown.");
} catch (DuplicateKeyException e) {
  assertEquals("Error code doesn't match", 123, e.getErrorCode());
} finally {
  //cleanup
  dao.delete(obj);
}

As noted in another comment. Having a test to fail until you can finish implementing it sounds reasonable as well.

如另一条评论所述。在完成实施之前测试失败听起来也很合理。

回答by Raphael

In concurrent and/or asynchronous settings, you may want to verify that certain methods (e.g. delegates, event listeners, response handlers, you name it) are notcalled. Mocking frameworks aside, you can call fail()in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.

在并发和/或异步设置中,您可能想要验证某些方法(例如委托、事件侦听器、响应处理程序,您自己命名)未被调用。撇开模拟框架不谈,您可以调用fail()这些方法来使测试失败。在这种情况下,超时超时是另一种自然的故障条件。

For example:

例如:

final CountDownLatch latch = new CountDownLatch(1);

service.asyncCall(someParameter, new ResponseHandler<SomeType>() {
    @Override
    public void onSuccess(SomeType result) {
        assertNotNull(result);
        // Further test assertions on the result
        latch.countDown();
    }

    @Override
    public void onError(Exception e) {
        fail(exception.getMessage());
        latch.countDown();
    }
});

if ( !latch.await(5, TimeUnit.SECONDS) ) {
    fail("No response after 5s");
}