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

发布于 2024-09-26 03:08:06 字数 31 浏览 4 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

素染倾城色 2024-10-03 03:08:06

在某些情况下,我发现它很有用:

  • 标记一个不完整的测试,因此它会失败并警告您,直到您完成它
  • 以确保抛出异常:

<前><代码>尝试{
// 做事...
失败(“未抛出异常”);
}捕获(异常e){
断言True(e.hasSomeFlag());
}

注意:

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

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

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());
}

Note:

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

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

萌梦深 2024-10-03 03:08:06

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

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

Let's say you are writing a test case for a negative flow where the code being tested should raise an exception.

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}
白况 2024-10-03 03:08:06

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

类似下面的伪代码:

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

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
    }
}
苏璃陌 2024-10-03 03:08:06

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

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

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
}
空城之時有危險 2024-10-03 03:08:06

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

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

  1. Passed 状态: 被测函数成功执行并返回
    数据符合预期
  2. 未通过:测试中的函数执行成功,但
    返回的数据不符合预期
  3. 失败:函数未成功执行,这不是

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

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

我对第三种情况使用失败操作。

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

  1. 传递案例: a = new Interger(1), b= new Integer(2) 和函数返回 3
  2. 未通过案例: a = new Interger(1)、b= new Integer(2) 且函数返回 3 以外的 soem 值
  3. 失败案例:a = null 、 b= null 且函数抛出 NullPointerException

This is how I use the Fail method.

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

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.

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

  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
绮烟 2024-10-03 03:08:06

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

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

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

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

新一帅帅 2024-10-03 03:08:06

在并发和/或异步设置中,您可能想要验证某些方法(例如委托、事件侦听器、响应处理程序,凡是您能想到的)没有被调用。除了模拟框架之外,您可以在这些方法中调用 fail() 来使测试失败。在这种情况下,过期超时是另一种自然的失败情况。

例如:

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");
}

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 not called. Mocking frameworks aside, you can call fail() in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.

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");
}
顾冷 2024-10-03 03:08:06

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

而 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);
}

正如另一条评论中指出的。在完成实施之前让测试失败听起来也很合理。

The most important use case is probably exception checking.

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

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.

季末如歌 2024-10-03 03:08:06

这是一个简短的 Junit 5 示例,说明了单元测试失败和错误之间的区别。 (请注意,JUnit 5 有一个 assertThrows(…) 方法,因此很少需要使用 fail(…) 来指示不存在异常。)

假设我有一个方法 deleteFileTree(Path fileTreeRoot) 来删除目录,即使其中有文件。我的方法有效,只是我第一次编写它时我假设有一个目录要删除。在现场,我遇到了一个情况,该目录一开始就不存在,并且抛出了 NoSuchFileException。我希望这个方法是幂等的(如果我们尝试删除丢失的目录,或者删除该目录两次,这不是问题),所以我解决了这个问题。集成测试如下所示:

@Test
void verifyDeleteFileTreeThrowsNoExceptionIfPathDoesNotExist(@TempDir Path tempDir) throws IOException {
  try {
    final Path missingDir = tempDir.resolve("missing");
    assertThat(Files.deleteFileTree(missingDir), is(missingDir));
  } catch(final NoSuchFileException noSuchFileException) {
    fail("Should not throw exception if path is already missing.", noSuchFileException);
  }
}

在本例中,测试是为了确保它不会抛出 NoSuchFileException;如果是,则测试失败。但是,如果抛出一些其他异常,则测试会出现错误,因为问题是意外的并且与我正在测试的内容无关,即测试无法正常工作。

如果我没有检查 NoSuchFileException 并使用 fail(...),则测试将指示错误情况。这在语义上是不正确的,因为测试工作正常并且没有错误,相反,我正在测试的方法未通过测试。

Here is a short Junit 5 example that illustrates the difference between unit test failure and error. (Note that JUnit 5 has a assertThrows(…) method, so the use of fail(…) to indicate the absence of an exception is seldom needed.)

Let's say I have a method deleteFileTree(Path fileTreeRoot) to delete a directory even if it has files in it. My method works, except that the first time I wrote it I assumed there was a directory to delete. In the field I ran into a case where the directory didn't exist to begin with, and it threw a NoSuchFileException. I want this method to be idempotent (it's not a problem if we try to delete a directory that is missing, or if we delete the directory twice), so I fixed the problem. The integration test looks like this:

@Test
void verifyDeleteFileTreeThrowsNoExceptionIfPathDoesNotExist(@TempDir Path tempDir) throws IOException {
  try {
    final Path missingDir = tempDir.resolve("missing");
    assertThat(Files.deleteFileTree(missingDir), is(missingDir));
  } catch(final NoSuchFileException noSuchFileException) {
    fail("Should not throw exception if path is already missing.", noSuchFileException);
  }
}

In this case the test was to make sure it did not throw NoSuchFileException; if it does, the test fails. But if some other exception is thrown, the test has an error, as the problem is something unexpected and unrelated to what I'm testing—i.e. the test is not working correctly.

If I had not have checked for NoSuchFileException and used fail(…), the test would have indicated an error condition. This would not have been correct semantically, as the test was working correctly and had no error—rather, the method I was testing failed the test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文