使用junit @Rule,expectCause()和hamcrest匹配器 [英] Using junit @Rule, expectCause() and hamcrest matchers

查看:173
本文介绍了使用junit @Rule,expectCause()和hamcrest匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试:

@Rule
public ExpectedException thrown = ExpectedException.none();
...
@Test
public void testMethod()
{
    final String error = "error message";
    Throwable expectedCause = new IllegalStateException(error);
    thrown.expectCause(org.hamcrest.Matchers.<Throwable>equalTo(expectedCause));
    someServiceThatTrowsException.foo();
}

当通过mvn运行测试方法时,我收到错误:

When run via mvn the test method, I'm getting the error:


java.lang.NoSuchMethodError:
org.junit.rules.ExpectedException.expectCause(Lorg / hamcrest / Matcher;)V

java.lang.NoSuchMethodError: org.junit.rules.ExpectedException.expectCause(Lorg/hamcrest/Matcher;)V

测试编译正常。

请帮帮我,无法理解如何测试异常的原因?

Please help me, cannot understand how to test the cause of the exception?

推荐答案

以这种方式试试:

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

@Test public void testMethod() throws Throwable {
    final String error = "error message";
    Throwable expectedCause = new IllegalStateException(error);
    thrown.expectCause(IsEqual.equalTo(expectedCause));
    throw new RuntimeException(expectedCause);
}

考虑不要通过等号检查原因,而是通过IsInstanceOf和/或comapring检查必要时的异常消息。通过equals比较原因也检查堆栈跟踪,这可能比您想要测试/检查的更多。例如:

Consider not to check against the cause by equals but by IsInstanceOf and / or comapring the exception message if necessary. Comparing the cause by equals check the stacktrace as well, which may be more than you would like to test / check. Like this for example:

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

@Test public void testMethod() throws Throwable {
    final String error = "error message";
    thrown.expectCause(IsInstanceOf.<Throwable>instanceOf(IllegalStateException.class));
    thrown.expectMessage(error);
    throw new RuntimeException(new IllegalStateException(error));
}

这篇关于使用junit @Rule,expectCause()和hamcrest匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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