I'm trying to unit test a specific scenario that requires me to throw an exception with a specific stack trace element.
Basically I do:
final RuntimeException exception = new RuntimeException();
exception.setStackTrace(
new StackTraceElement[] {
new StackTraceElement(
Claims.class.getCanonicalName(),
"add",
"Claims.java",
123
)
}
);
Mockito.doThrow(exception).when(stk).process(project, claim);
But in the method under test the exception thrown doesn't contain this element, it contains a stack trace to the unit test class.
Is it possible for Mockito to throw the exception exactly as I want? Or will it always override the stack trace?
The act of throwing an exception will rewrite its stacktrace, even if it's done by doThrow.
One way around this is not to use a real exception, but to mock it:
RuntimeException exception = mock(RuntimeException.class);
when(exception.getStackTrace()).thenReturn(
new StackTraceElement[] {
new StackTraceElement(
Claims.class.getCanonicalName(),
"add",
"Claims.java",
123
)
}
);
Another way of doing this is to use doAnswer or thenAnswer to throw the exception instead:
Mockito.doAnswer((invocation) -> {
throw exception;
}).when(stk).process(project, claim);
This will keep your original stack trace intact instead of having Mockito mangle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With