mardi 1 décembre 2015

Use Mockito to unit test a function which calls async function

I have a method which calls async function:

public class MyService {
  ...
  public void uploadData() {
    MyPool.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    boolean suc = upload();
                }
            });
        }
}

I want to unit test this function with Mockito, I tried:

MyPool mockMyPool = Mockito.mock(MyPool.class);
ThreadPool mockThreadPool = Mockito.mock(ThreadPool.class);
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

when(mockMyPool.getThreadPool()).thenReturn(mockThreadPool);
MyService service = new MyService();

// run the method under test
service.uploadData();

// set the runnableCaptor to hold your callback
verify(mockThreadPool).execute(runnableCaptor.capture());

But I got error:

org.mockito.exceptions.verification.WantedButNotInvoked: 
Wanted but not invoked:
threadPool.execute(
    <Capturing argument>
);

Why I got this error, how to unit test uploadData() function with Mockito?

Aucun commentaire:

Enregistrer un commentaire