java - 具有返回 void 的可运行参数的模拟方法

标签 java unit-testing junit mocking mockito

这是方法的接口(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/

相关文章:

面向非线性应用层协议(protocol)的Java服务器程序

java - 为什么我将应用程序导出到 Jar 后得到 "A Java Exception has occurred"?

ios - OCMock:在本地声明的对象上模拟方法

c# - 为单元测试 stub ASP.NET Page.Form

android - DaggerMock - 如何让 Dagger 在测试用例中提供对象

java - Windows SmartScreen 阻止我的 EXE 文件。有什么解决方案吗?

Java - JList.getSelectedValuesList() 在 jar 文件中不起作用

unit-testing - 如何定义模拟方法被调用零次

java - JUnit异常 "Object is not an instance of declaring method"

java - 找不到导入 junit jupiter api