我正在使用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此工作.
Daw*_*ica 14
要做到这一点,最好的办法是与verifyNoMoreInteractions和ignoreStubs静态方法.在测试的"行为"部分之后调用这些; 如果调用了任何未修改的方法但未经过验证,您将会失败.
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中有所描述,尽管我认为那里的代码示例目前包含错误打印.
| 归档时间: |
|
| 查看次数: |
5827 次 |
| 最近记录: |