Take a look at the Mockito API docs .
(看一下Mockito API文档 。)
As the linked document mentions (Point # 12) you can use any of the doThrow()
, doAnswer()
, doNothing()
, doReturn()
family of methods from Mockito framework to mock void methods. (正如链接文档中提到的那样(第12点),您可以使用doThrow()
中的doThrow()
, doAnswer()
, doNothing()
, doReturn()
系列方法中的任何一种来模拟void方法。)
For example,
(例如,)
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
(或者如果您想将其与后续行为结合起来,)
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
(假设您正在模拟以下类World中的setter setState(String s)
,则代码使用doAnswer
方法来模拟setState
。)
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…