这是方法的接口(interface):
void startWatch(MethodToWatch methodName, UUID uniqueID, Runnable toRun);
这是实现:
public void startWatch(MethodToWatch methodName, UUID uniqueID, Runnable toRun) {
this.startWatch(methodName, uniqueID);
start();
toRun.run();
stop();
}
我想用这样的东西来模拟这个方法:
IPerformanceStopWatch mock = mock(IPerformanceStopWatch.class);
when(performanceStopWatchFactory.getStartWatch()).thenReturn(mock);
when(mock.startWatch(any(), any(), any())).thenAnswer(new Answer<void>() {
@Override
public void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Runnable torun = (Callable)args[2];
torun.run();
return;
}
});
问题是 when(...) 无法获取返回值为 void 的方法。
如何在不使用 spy 的情况下使用此方法?
最佳答案
使用doAnswer()
:
// It is supposed here that Mockito.doAnswer is statically imported
doAnswer(...).when(mock).startWatch(etc);
您可以重复使用已有的答案,这很好。
关于java - 具有返回 void 的可运行参数的模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34116895/