Search code examples
mockitorx-javavert.xvertx-verticle

Testing asynchronous Vertx and RxJava methods using mockito


I have a class which sends a message on the vert.x event bus, and then handles the reply from the event bus consumer. When the class runs, it calls methods on objects which are passed to it either in the constructor or specific method calls.

In order to verify that the methods on the object passed in are indeed called, the object is mocked using Mockito. Here is the basic structure of the test class:

@RunWith(VertxUnitRunner.class)
public class MyTest {

    @Rule
    public RunTestOnContext rule = new RunTestOnContext(new VertxOptions());

    @Test
    public void test(TestContext context) {

       Runnable r = new Runnable() {
          @Override
            public void run() {
                // Create an event bus consumer for testing
                // ...

                // Create the class to be tested
                Dao dao = new Dao();
                DbManager dbManager = Mockito.mock(DbManager.class);
                dao.save(dbManager);
            }
       }

       Thread t2 = new Thread(r);
       t2.start();
       t2.join();

       Mockito.verify(dbManager, ...
       async.complete();
    }
}

This works only some of the time. The issue is that when the dao class sends an asynchronous message to the vert.x event bus and handles the response, this is all happening in a different thread to the one which the join() call is waiting on, and therefore the Mockito.verify could take place before the threads which vertx manages have completed.

What is the best way to structure these tests, so that Mockito will wait until all dependent asynchronous threads have finished?

Thanks


Solution

  • The only thing that comes to my mind is to verify with timeout, it means that mockito will wait for a specified period of time for interaction instead of failing immediately.

    Mockito.verify(dbManager, Mockito.timeout(5000)).....