如何使用 Mockito 模拟 void 方法 [英] How to mock void methods with Mockito
问题描述
如何使用 void 返回类型模拟方法?
How to mock methods with void return type?
我实现了一个观察者模式,但我不能用 Mockito 模拟它,因为我不知道如何.
I implemented an observer pattern but I can't mock it with Mockito because I don't know how.
然后我试图在互联网上找到一个例子,但没有成功.
And I tried to find an example on the Internet but didn't succeed.
我的班级是这样的:
public class World {
List<Listener> listeners;
void addListener(Listener item) {
listeners.add(item);
}
void doAction(Action goal,Object obj) {
setState("i received");
goal.doAction(obj);
setState("i finished");
}
private string state;
//setter getter state
}
public class WorldTest implements Listener {
@Test public void word{
World w= mock(World.class);
w.addListener(this);
...
...
}
}
interface Listener {
void doAction();
}
系统不是通过模拟触发的.
The system is not triggered with mock.
我想显示上面提到的系统状态.并根据它们做出断言.
I want to show the above-mentioned system state. And make assertions according to them.
推荐答案
看一看 Mockito API 文档.正如链接文档中提到的(第 12 点),您可以使用任何 doThrow()
、doAnswer()
、doNothing()
、doReturn()
来自 Mockito 框架的方法系列,用于模拟 void 方法.
Take a look at the Mockito API docs. 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.
例如
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();
假设您正在考虑在下面的类 World 中模拟 setter setState(String s)
是代码使用 doAnswer
方法来模拟 setState代码>.
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 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());
这篇关于如何使用 Mockito 模拟 void 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!