【发布时间】:2023-03-25 07:30:01
【问题描述】:
我正在编写一些 JUnit 测试来验证是否抛出了 MyCustomException 类型的异常。但是,此异常多次包含在其他异常中,例如在 InvocationTargetException 中,而后者又被包装在 RuntimeException 中。
确定 MyCustomException 是否以某种方式导致我实际捕获的异常的最佳方法是什么?我想做这样的事情(见下划线):
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。)
关闭: 好的,我想确实没有绕过实用方法 :-) 感谢所有回复的人!
【问题讨论】:
标签: java spring exception exception-handling nested-exceptions