在 Java 中,如何使用 JUnit 验证抛出的异常? [英] In Java how can I validate a thrown exception with JUnit?

查看:30
本文介绍了在 Java 中,如何使用 JUnit 验证抛出的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为 Java API 编写单元测试时,您可能希望对异常执行更详细的验证.IE.比 JUnit 提供的 @test 注释提供的更多.

When writing unit tests for a Java API there may be circumstances where you want to perform more detailed validation of an exception. I.e. more than is offered by the @test annotation offered by JUnit.

例如,考虑一个类,它应该从其他接口捕获异常,包装该异常并抛出包装的异常.您可能需要验证:

For example, consider an class that should catch an exception from some other Interface, wrap that exception and throw the wrapped exception. You may want to verify:

  1. 引发包装异常的确切方法调用.
  2. 包装器异常将原始异常作为其原因.
  3. 包装器异常的消息.

这里的主要观点是您希望在单元测试中对异常进行额外的验证(而不是争论是否应该验证诸如异常消息之类的东西).

The main point here is that you want to be perf additional validation of an exception in a unit test (not a debate about whether you should verify things like the exception message).

对此有什么好的方法?

推荐答案

在 JUnit 4 中,可以使用 ExpectedException 规则.

In JUnit 4 it can be easily done using ExpectedException rule.

这是来自 javadocs 的示例:

Here is example from javadocs:

// These tests all pass.
public static class HasExpectedException {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsNothing() {
        // no exception expected, none thrown: passes.
    }

    @Test
    public void throwsNullPointerException() {
        thrown.expect(NullPointerException.class);
        throw new NullPointerException();
    }

    @Test
    public void throwsNullPointerExceptionWithMessage() {
        thrown.expect(NullPointerException.class);
        thrown.expectMessage("happened?");
        thrown.expectMessage(startsWith("What"));
        throw new NullPointerException("What happened?");
    }
}

这篇关于在 Java 中,如何使用 JUnit 验证抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆