我有一个测试:
@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 测试方法运行时,我收到错误:
java.lang.NoSuchMethodError:
org.junit.rules.ExpectedException.expectCause(Lorg/hamcrest/Matcher;)V
测试编译良好。
请帮助我,不明白如何测试异常原因?
试试这样:
@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);
}
考虑不要通过 equals 来检查原因,而是通过 IsInstanceOf 和/或在必要时共同映射异常消息。通过 equals 比较原因也检查堆栈跟踪,这可能比您想要测试/检查的更多。例如这样:
@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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)