调用unmocked方法时抛出RuntimeException

Hli*_*lib 25 java mockito

我正在使用mockito.我想RuntimeException在调用unmocked方法时抛出.有没有办法做到这一点?

Tom*_*lst 27

您可以为模拟设置默认答案.所有未存根的方法都将使用此默认答案.

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" );
    }

}
Run Code Online (Sandbox Code Playgroud)

请注意,您不能使用when此功能,因为此方法之前被调用when(mockito when()调用如何工作?)并且它将RuntimeException在模拟进入存根模式之前抛出.

因此,您必须使用doReturn此工作.

  • 你必须使用`doReturn`而不是`when`.我用这个解决方案编辑了我的答案. (4认同)
  • 谢谢!但是当我插入'when(someClass.unmpokedMethod()).thanReturn("huerga")'时,它继续抛出异常 (3认同)

Daw*_*ica 14

要做到这一点,最好的办法是与verifyNoMoreInteractionsignoreStubs静态方法.在测试的"行为"部分之后调用这些; 如果调用了任何未修改的方法但未经过验证,您将会失败.

verifyNoMoreInteractions(ignoreStubs(myMock));
Run Code Online (Sandbox Code Playgroud)

这在https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#ignore_stubs_verification中有所描述,尽管我认为那里的代码示例目前包含错误打印.

  • 如果由于调用unmocked方法导致的空取消引用导致测试在此之前模糊不清,则无效. (8认同)