Search code examples
javamockitoawaitility

How can I verify in a unit test that a method will be executed asynchronously i.e. in a separate thread?


The following method calls the method serveThis() of a service synchronously and the method serveThat() in a separate thread i.e. asynchronously:

public void doSomething() {
    service.serveThis();
    new Thread(() -> service.serveThat()).start();
}

I want to verify in a unit test that service.serveThat() will be executed asynchronously as according to the specification it must not be executed synchronously. So, I want to prevent that later on someone just removes starting a new thread like this:

public void doSomething() {
    service.serveThis();
    // This synchronous execution must cause the test to fail
    service.serveThat();
}

Solution

  • In order to achieve that I use Mockito:

    Thread threadServeThatRunsOn;
    
    @Test
    public void serveThatWillBeExecutedAsynchronously() throws Exception {
        doAnswer(invocation -> {
            threadServeThatRunsOn = Thread.currentThread();
            return null;
        }).when(mockService).serveThat();
    
        testObject.doSomething();
    
        verify(mockService, timeout(200)).serveThat();
        assertNotEquals(threadServeThatRunsOn, Thread.currentThread());
    }
    

    Now, if someone would modify doSomething()so that service.serveThat() would run synchronously, then this test would fail.