Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

how can i moke this method without using spy?

like image 402
USer22999299 Avatar asked Mar 09 '26 15:03

USer22999299


1 Answers

Use 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.

like image 141
fge Avatar answered Mar 11 '26 06:03

fge