我有一个类想要进行单元测试,它有一个依赖项 Foo,我想模拟它。此类 Foo 有时会在调用某个方法时触发事件。但不知道如何模拟 Foo 类来获得这种行为。
那么,我如何模拟 Foo 类,使它的行为类似于以下代码?到目前为止,我使用了 Mockito,但如果mockito 不提供所需的功能,我会开放新框架。
//This is how the class Foo should act when it is mocked
public class Foo()
{
private Listener listener;
public void addListener(Listener listener)
{
this.listener = listener;
}
public void callMethodWhichMayFireAnEvent()
{
listener.event();
}
}
最佳答案
为了得到你所要求的(可能是也可能不是你真正需要的),你可以使用一个答案......
final Listener listener = ...; // put your listener here
Foo fooMock = Mockito.mock(Foo.class);
Mockito.doAnswer( new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
listener.event(); // this calls your listener
return null; // actual Method is void, so this will be ignored anyway
}
}).when( fooMock.callMethodWhichMayFireAnEvent() );
所以,每当 fooMock.callMethodWhichMayFireAnEvent()
被调用时,它会调用event()
你的方法listener
对象。
关于java - 模拟实例触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34435902/