Yan*_*yer 26 java spring exception-handling exception nested-exceptions
我正在编写一些JUnit测试,以验证是否抛出了类型MyCustomException的异常.但是,此异常多次包含在其他异常中,例如在InvocationTargetException中,而InvocationTargetException又包含在RuntimeException中.
什么是确定MyCustomException是否以某种方式导致我实际捕获的异常的最佳方法?我想做这样的事情(见下划线):
Run Code Online (Sandbox Code Playgroud)try { doSomethingPotentiallyExceptional(); fail("Expected an exception."); } catch (RuntimeException e) { if (!e.wasCausedBy(MyCustomException.class) fail("Expected a different kind of exception."); }
我想避免getCause()深入调用一些"层",以及类似的丑陋工作.有更好的方法吗?
(显然,Spring有NestedRuntimeException.contains(Class),它可以做我想要的 - 但我没有使用Spring.)
CLOSED: 好的,我猜有一个实用方法真的没有绕过:-)感谢所有回复的人!
Pat*_*oos 32
如果您使用的是Apache Commons Lang,那么您可以使用以下内容:
(1)当原因应完全符合指定类型时
if (ExceptionUtils.indexOfThrowable(exception, ExpectedException.class) != -1) {
// exception is or has a cause of type ExpectedException.class
}
Run Code Online (Sandbox Code Playgroud)
(2)当原因应该是指定类型或其子类类型时
if (ExceptionUtils.indexOfType(exception, ExpectedException.class) != -1) {
// exception is or has a cause of type ExpectedException.class or its subclass
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*ine 27
你为什么要避免getCause.当然,您可以自己编写一个执行任务的方法,例如:
public static boolean isCause(
Class<? extends Throwable> expected,
Throwable exc
) {
return expected.isInstance(exc) || (
exc != null && isCause(expected, exc.getCause())
);
}
Run Code Online (Sandbox Code Playgroud)