我的代码中有一个如下所示的方法:
action.onResult(new Handler<MyClass>() {
@Override
public MyClass handle() { // Do something here }
}
}
我希望能够模拟它(使用 Mockito)。像这样的事情:
when(mockedAction.onResult(any(Handler.class))).thenReturn(firstArg.handle());
意思是,我想调用发送到方法onResult
的参数的handle
方法。我无法模拟处理程序,因为它使用调用类的内部方法(我考虑过使用私有(private)类,但尚未达到足够好的解决方案)
动机:这是在同步区域中使用的异步回调机制。我想模拟对处理程序本身的调用,以便在代码中同步继续流程。
最佳答案
好的,未经测试,但是对于这种情况,ArgumentCaptor
可能会被使用:
final ArgumentCaptor<Handler> captor = ArgumentCaptor.forClass(Handler.class);
when(mock.onResult(captor.capture())).thenReturn(captor.getValue().handle());
但是不确定捕获者是否有“时间”在这里初始化。
关于java - 使用模拟方法参数来模拟后续步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456385/