使用返回void的runnable参数进行模拟方法

时间:2015-12-06 11:28:15

标签: java unit-testing junit mocking mockito

这是方法的界面:

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;
    }
});

问题是当(...)无法获得返回值为void的方法时。

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

1 个答案:

答案 0 :(得分:4)

使用doAnswer()

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

你可以重复使用你的答案,这很好。

相关问题