Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito.doThrow with custom stacktrace

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?

like image 358
Krzysztof Krasoń Avatar asked May 09 '26 20:05

Krzysztof Krasoń


2 Answers

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
        )
    }
);
like image 87
Mureinik Avatar answered May 11 '26 08:05

Mureinik


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.

like image 36
Krease Avatar answered May 11 '26 08:05

Krease



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!