如何模拟具有 void 返回类型的方法?
我实现了一个观察者模式,但我不能用 Mockito 模拟它,因为我不知道怎么做。
并且我试图在网上找例子但是没有成功。
我的课看起来像这样:
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();
}
系统不会被 mock 触发。
我想显示上述系统状态。并根据它们做出断言。
原文由 ibrahimyilmaz 发布,翻译遵循 CC BY-SA 4.0 许可协议
查看 Mockito API 文档。 As the linked document mentions (Point # 12) you can use any of the
doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods从 Mockito 框架到模拟 void 方法。例如,
或者如果你想将它与后续行为结合起来,
假设您正在查看模拟 setter
setState(String s)
在下面的类 World 中,代码使用doAnswer
方法来模拟setState
.