调用unmocked方法时抛出RuntimeException
我正在使用mockito。 我想在调用unmocked方法时抛出RuntimeException
。 有没有办法做到这一点?
您可以为模拟设置默认答案。 所有未存根的方法都将使用此默认答案。
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
请注意, when
使用此functionwhen
无法使用,因为该方法在之前调用when
( mockto when()调用如何工作? )并且它将在模拟进入存根模式之前抛出RuntimeException
。
因此,您必须使用doReturn
才能工作。
执行此操作的最佳方法是使用verifyNoMoreInteractions
和ignoreStubs
静态方法。 在测试的“行为”部分之后调用这些; 如果调用了任何未被修改的方法但未经过validation,您将会失败。
verifyNoMoreInteractions(ignoreStubs(myMock));
这在https://static.javadoc.io/org.mockito/mockito-core/2.8.47/org/mockito/Mockito.html#ignore_stubs_verification中有所描述,但我相信那里的代码示例目前包含错误打印。
您模拟整个类,结果是所有方法都将返回null。
然后,您可以使用doReturn(...)
来更改该行为。 类似地,您可以使用doThrow(...)
来生成(因为我只记得void
)方法抛出exception。
这是否回答你的问题?