我如何用断言JUnit测试批注我的异常信息? [英] How do I assert my exception message with JUnit Test annotation?

查看:245
本文介绍了我如何用断言JUnit测试批注我的异常信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了以 @Test 标注了一些JUnit测试。如果我的测试方法抛出检查异常,如果我想沿着断言消息,异常,有没有办法用JUnit这样做 @Test 标注?据我所知,JUnit的4.7不提供此功能,但没有任何未来的版本提供呢?我知道在.net中,您可以断言的消息和异常类。寻找在Java世界中类似的功能。

这是我想要的:

  @Test(预期= RuntimeException.class,消息=雇员ID为空)
公共无效shouldThrowRuntimeExceptionWhenEmployeeIDisNull(){}


解决方案

您可以使用 @rule 批注与<一个href=\"http://junit.org/javadoc/latest/org/junit/rules/ExpectedException.html\"><$c$c>ExpectedException,像这样的:

  @rule
公众的ExpectedException expectedEx = ExpectedException.none();@测试
公共无效shouldThrowRuntimeExceptionWhenEmployeeIDisNull()抛出异常{
    expectedEx.expect(RuntimeException.class);
    expectedEx.expectMessage(员工ID为空);
    //做一些事情,应该抛出异常...
}

请注意,在的ExpectedException 文档的例子是(目前)错误 - 没有公共的构造,所以你必须使用 ExpectedException.none( )

I have written a few JUnit tests with @Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exception, is there a way to do so with JUnit @Test annotation? AFAIK, JUnit 4.7 doesn't provide this feature but does any future versions provide it? I know in .NET you can assert the message and the exception class. Looking for similar feature in the Java world.

This is what I want:

@Test (expected = RuntimeException.class, message = "Employee ID is null")
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() {}

解决方案

You could use the @Rule annotation with ExpectedException, like this:

@Rule
public ExpectedException expectedEx = ExpectedException.none();

@Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
    expectedEx.expect(RuntimeException.class);
    expectedEx.expectMessage("Employee ID is null");
    // do something that should throw the exception...
}

Note that the example in the ExpectedException docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none().

这篇关于我如何用断言JUnit测试批注我的异常信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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