[FIXED] Mockito verify asynchronous methods


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) {

    // queue Runnable in worker thread to do something
    BackgroundWorker.queueTask(new Runnable() {
        public void run() {

I need to verify doSomething() is called so I write a unit 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?


It seems we have 2 solutions:

  • First is verify with timeout()

  • Second is create a "fake" BackgroundWorker (in src/test folder) to call Runnable#run() directly, without queuing into background thread.

Answered By – nhoxbypass

Answer Checked By – Candace Johnson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published