I am writing some JUnit tests that verify that an exception of type MyCustomException
is thrown. However, this exception is wrapped in other exceptions a number of times, e.g. in an InvocationTargetException, which in turn is wrapped in a RuntimeException.
What's the best way to determine whether MyCustomException somehow caused the exception that I actually catch? I would like to do something like this (see underlined):
try { doSomethingPotentiallyExceptional(); fail("Expected an exception."); } catch (RuntimeException e) { if (!e.
wasCausedBy(MyCustomException.class) fail("Expected a different kind of exception."); }
I would like to avoid calling getCause()
a few "layers" deep, and similar ugly work-arounds. Is there a nicer way?
(Apparently, Spring has NestedRuntimeException.contains(Class), which does what I want - but I'm not using Spring.)
CLOSED: OK, I guess there's really no getting around a utility method :-) Thanks to everybody who replied!