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.
Why would you want to avoid getCause
. You can, of course, write yourself a method to perform the task, something like:
public static boolean isCause(
Class<? extends Throwable> expected,
Throwable exc
) {
return expected.isInstance(exc) || (
exc != null && isCause(expected, exc.getCause())
);
}