Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw a RuntimeException when invoking an unstubbed method

Tags:

java

mockito

I'm using Mockito. I want to throw a RuntimeException when an unstubbed method is called.

Is there any way to do this?

like image 741
Hlib Avatar asked Apr 05 '13 13:04

Hlib


2 Answers

You can set a default answer for a mock. All methods that aren't stubbed will use this default answer.

public void testUnstubbedException() {
    // Create a mock with all methods throwing a RuntimeException by default
    SomeClass someClass = mock( SomeClass .class, new RuntimeExceptionAnswer() );

    doReturn(1).when(someClass).getId(); // Must use doReturn

    int id = someClass.getId(); // Will return 1

    someClass.unstubbedMethod(); // Will throw RuntimeException
}

public static class RuntimeExceptionAnswer implements Answer<Object> {

    public Object answer( InvocationOnMock invocation ) throws Throwable {
        throw new RuntimeException ( invocation.getMethod().getName() + " is not stubbed" );
    }

}

Note that you cannot use when with this functionality, since the method is called before when (How does mockito when() invocation work?) and it will throw a RuntimeException before the mock goes into stubbing mode.

Therefore, you must use doReturn for this to work.

like image 92
Tom Verelst Avatar answered Oct 19 '22 10:10

Tom Verelst


The best way to do this is with the verifyNoMoreInteractions and ignoreStubs static methods. Call these after the "act" part of your test; and you'll get a failure if any unstubbed methods were called but not verified.

verifyNoMoreInteractions(ignoreStubs(myMock));

This is described at https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#ignore_stubs_verification although I believe that the code example there currently contains a misprint.

like image 15
Dawood ibn Kareem Avatar answered Oct 19 '22 11:10

Dawood ibn Kareem