简体   繁体   English

具有可返回空值的可运行参数的模拟方法

[英]Mocking method with runnable arguments that return void

This is the interface of the method: 这是方法的接口:

void startWatch(MethodToWatch methodName, UUID uniqueID, Runnable toRun);

This is the implementation: 这是实现:

public void startWatch(MethodToWatch methodName, UUID uniqueID, Runnable toRun) {
        this.startWatch(methodName, uniqueID);
        start();
        toRun.run();
        stop();
    }

i would like to mock this method with something like this: 我想用这样的东西来模拟这个方法:

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

the problem is that when(...) cannot get a method with return value of void. 问题是when(...)无法获得返回值为void的方法。

how can i moke this method without using spy? 我如何不使用间谍就可以模仿这种方法?

Use doAnswer() : 使用doAnswer()

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

You can just reuse the answer you have, which is good. 您可以重复使用已有的答案,这很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM