具有 return void 的可运行参数的模拟方法

Mocking method with runnable arguments that return void

这是方法的接口:

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(...) 无法获得 return 值为 void 的方法。

如何在不使用间谍的情况下使用此方法?

使用doAnswer():

// It is supposed here that Mockito.doAnswer is statically imported
doAnswer(...).when(mock).startWatch(etc);

您可以重复使用已有的答案,这很好。