我正在编写一些 JUnit 测试来验证是否抛出了类型为 MyCustomException
的异常。但是,此异常多次包含在其他异常中,例如 InvocationTargetException,后者又包含在 RuntimeException 中。
确定 MyCustomException 是否以某种方式导致我实际捕获的异常的最佳方法是什么?我想做这样的事情(见下划线):
try {
doSomethingPotentiallyExceptional();
fail("Expected an exception.");
} catch (RuntimeException e) {
if (!e.是由 (MyCustomException.class)
fail("Expected a different kind of exception.");
}
我想避免调用 getCause()
一些“层”深,以及类似的丑陋解决方法。有更好的方法吗?
显然,Spring 有 NestedRuntimeException.contains(Class) ,它可以满足我的要求——但我没有使用 Spring。
原文由 Yang Meyer 发布,翻译遵循 CC BY-SA 4.0 许可协议
你为什么要避免
getCause
。当然,您可以自己编写一个方法来执行任务,例如: