jUnit 中的预期异常?

发布于 2024-07-25 19:14:05 字数 80 浏览 5 评论 0原文

是否有相当于 NUnit 的 ExpectedException 或 Assert.Throws<> 的东西? 在 jUnit 中?

Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?

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

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

发布评论

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

评论(3

ι不睡觉的鱼゛ 2024-08-01 19:14:05

您还可以考虑查看 ExpectedException 类,它提供了更丰富的异常匹配。

https://github.com/junit-team/junit/wiki/Exception-测试

您不仅可以匹配异常类,还可​​以将自定义匹配器应用于其消息。

You might also consider taking a look at the ExpectedException class which provides richer exception matching.

https://github.com/junit-team/junit/wiki/Exception-testing

Not only you can match the exception class but also you can apply custom matchers to its message.

无声静候 2024-08-01 19:14:05

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}
老旧海报 2024-08-01 19:14:05

如果您使用 Groovy 进行 junit 测试,您可以使用 应该失败

这是使用 junit3 风格的示例:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}

If you are using Groovy for your junit tests you can use shouldFail.

Here is an example using junit3 style:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文