我正在编写一些JUnit测试,验证是否抛出了MyCustomException
类型的异常。 然而,这种异常被其他异常包装了多次,例如在InvocationTargetException中被包装,然后又被包装在RuntimeException中。
如何最好地确定MyCustomException是否引起了实际捕获的异常?我想做类似于这样的事情(请参见下划线部分):
try {
doSomethingPotentiallyExceptional();
fail("Expected an exception.");
} catch (RuntimeException e) {
if (!e.</code>wasCausedBy<code>(MyCustomException.class)
fail("Expected a different kind of exception.");
}
我想避免在几个“层”深处调用getCause()
,以及类似的丑陋的解决方法。 有更好的方式吗?
显然,Spring有一个NestedRuntimeException.contains(Class),它可以实现我的需求 - 但我没有使用Spring。
ExceptionUtils.hasCause(e, ExpectedException.class)
- Gabriel