Ami*_*mir 6 java junit exception-handling hamcrest expected-exception
我正在尝试验证我的所有异常都是正确的.因为值被包装CompletableFutures,抛出ExecutionException的异常是因为我通常会检查的异常.快速举例:
void foo() throws A {
try {
bar();
} catch B b {
throw new A(b);
}
}
Run Code Online (Sandbox Code Playgroud)
所以foo()转换异常由抛出bar(),而所有这一切都内部完成CompletableFutures和AsyncHandlers(我不会复制整个代码,它只是供参考)
在我的单元测试中,我正在bar()抛出一个异常,并希望在调用时检查它是否正确转换foo():
Throwable b = B("bleh");
when(mock.bar()).thenThrow(b);
ExpectedException thrown = ExpectedException.none();
thrown.expect(ExecutionException.class);
thrown.expectCause(Matchers.allOf(
instanceOf(A.class),
having(on(A.class).getMessage(),
CoreMatchers.is("some message here")),
));
Run Code Online (Sandbox Code Playgroud)
到目前为止这么好,但我也想验证A异常的原因是异常B和having(on(A.class).getCause(), CoreMatchers.is(b))原因CodeGenerationException --> StackOverflowError
TL; DR:我如何得到预期异常的原因?
也许您应该尝试使用简单的hasProperty Matcher,以隔离问题:
thrown.expectCause(allOf(
instanceOf(A.class),
hasProperty("message", is("some message here")),
));
Run Code Online (Sandbox Code Playgroud)