I have an method that need to write test (I use instrumented androidTest
, but this also happen with JVM unit test):
void fooNeedToBeTested(String paramString) {
if(paramString.isEmpty())
return
// queue Runnable in worker thread to do something
BackgroundWorker.queueTask(new Runnable() {
@Override
public void run() {
repository.doSomething(paramString);
}
});
}
I need to verify doSomething()
is called so I write a unit test:
@Test
void testVerifyAsyncCallback() {
presenter.fooNeedToBeTested("string args");
Mockito.verify(repository).doSomething("string args");
}
But the problem is: the test finish executed before the async code inside run()
method has been reached. Then Mockito cannot verify it has been run or not.
So how can we tell test runner to wait for the async code to be executed, then inform Mockito to verify?
verify with timeout
.wait
your asking for). -- If you want to use another approach you could define alock
within thedoSomething
(by usingthenAnswer
) and actively block the test unitl this point has been reached,