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

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

问题描述

在为Java API编写单元测试时,您可能需要对异常执行更详细的验证。即比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. 包装器异常的消息。



<这里的主要内容是,您希望在单元测试中进一步验证异常(而不是关于您是否应该/ em>验证异常消息之类的争论)。

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天全站免登陆