如何使用mockito模拟void方法 [英] How to make mock to void methods with mockito

查看:1272
本文介绍了如何使用mockito模拟void方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用void返回类型模拟方法?



我实现了一个观察者模式,但是我无法用Mockito模仿它,因为我不知道如何。



<我尝试在互联网上找到一个例子,但没有成功。



我的班级看起来像

  public class World {

List< Listener>听众;

void addListener(Listener item){
listeners.add(item);
}

void doAction(行动目标,对象obj){
setState(我收到);
goal.doAction(obj);
setState(我完成);
}

私有字符串状态;
// setter getter state
}

公共类WorldTest实现Listener {

@Test public void word {
World w = mock (世界级);
w.addListener(this);
...
...

}
}

接口监听器{
void doAction();
}

系统不会被模拟触发。 =(
我想显示上面提到的系统状态。并根据它们进行断言。

解决方案

解决方案所谓的问题是使用 spy Mockito.spy(...)而不是模拟 Mockito.mock(..)



间谍使我们能够进行部分嘲弄.Mockito擅长此事。因为你的课程不完整,所以你在这个课程中模拟了一些必要的地方。


How to mock methods with void return type?

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.

My class looks like

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 are not triggered with mock. =( I want to show above mentioned system state. And make assertion according to them.

解决方案

The solution of so-called problem is to use a spy Mockito.spy(...) instead of a mock Mockito.mock(..).

Spy enables us to partial mocking. Mockito is good at this matter. Because you have class which is not complete, in this way you mock some required place in this class.

这篇关于如何使用mockito模拟void方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆