Is it possible to verify a mock method running in different thread in Mockito?
It is very likely that the Runnable
hasn't been executed yet by the asyncTaskExecutor
when you verify the invocation, resulting in a verification error in your unit test.
The best way to fix this is to join on the generated thread and wait for execution before verifying the invocations.
If you cannot get the instance of the thread, a possible work around is to mock the asyncTaskExecutor
and implement it so it will execute the runnable directly.
private ExecutorService executor;
@Before
public void setup() {
executor = mock(ExecutorService.class);
implementAsDirectExecutor(executor);
}
protected void implementAsDirectExecutor(ExecutorService executor) {
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Exception {
((Runnable) invocation.getArguments()[0]).run();
return null;
}
}).when(executor).submit(any(Runnable.class));
}
I had the same issue and played around with the timeout argument http://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html#22 but with argument 0 like in
verify(someClass, timeout(0)).someMethod(any(someParameter.class));
And it works. I assume that the testing thread yields, and therefore the other thread has an opportunity to do its work, calling the mocks appropriately. Still it smells like a hack.