【问题标题】:Mocking method with runnable arguments that return void具有返回 void 的可运行参数的模拟方法
【发布时间】:2015-12-06 11:28:14
【问题描述】:

这是方法的接口:

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的方法。

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

【问题讨论】:

    标签: java unit-testing junit mocking mockito


    【解决方案1】:

    使用doAnswer():

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

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

    【讨论】:

    • 呃?它一直对我有用。怎么没用?你的测试是什么?
    • 遇到了另一个问题 :) 似乎可以正常工作 :) 谢谢!
    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多