Throw a RuntimeException when invoking an unstubbed method

后端 未结 4 763
滥情空心
滥情空心 2020-12-09 02:44

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

Is there any way to do this?

4条回答
  •  余生分开走
    2020-12-09 03:13

    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 {
    
        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.

    提交回复
    热议问题