08-02-2023, 12:34 PM
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):
<pre><code>
try {
doSomethingPotentiallyExceptional();
fail("Expected an exception.");
} catch (RuntimeException e) {
if (!e.</code><u>wasCausedBy</u><code>(MyCustomException.class)
fail("Expected a different kind of exception.");
}
</code></pre>
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)][1], which does what I want - but I'm not using Spring.
[1]:
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):
<pre><code>
try {
doSomethingPotentiallyExceptional();
fail("Expected an exception.");
} catch (RuntimeException e) {
if (!e.</code><u>wasCausedBy</u><code>(MyCustomException.class)
fail("Expected a different kind of exception.");
}
</code></pre>
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)][1], which does what I want - but I'm not using Spring.
[1]:
[To see links please register here]