Search code examples
javaunit-testingmockitoexecutorservicethreadpoolexecutor

Mockito Verify "times" shows lesser count then actual when run with ExecutorService


I am trying to unit test a code run containing executor service where the api is getting called twice or more depending on the no of devices in the list. When I try to unit test this from console, Mockito verify fails throwing an error that the Api is called only once while I passed list of devices. However, when I debug in intellij, it works correctly and gets executed and verified according to the no of devices in the list.

Following is the code

final ExecutorService executor = new ThreadPoolExecutor(MAX_THREADS,
    TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());

DeviceList.stream().forEach(device -> executor.execute(() ->
    GatewayToTest.deliver(device, id, testObject)));

Unit test code:

verify(GatewayToTest, times(devices.size()))
    .deliver(any(Device.class), anyString(), any(TestObject.class));

In the above code, GatewayToTest is called only once when I run unit tests in console.


Solution

  • The executions run asynchronously, so you cannot guarantee that all the calls to GatewayToTest.deliver happen before verify. Try to await for termination after submitting the tasks for execution:

    executor.awaitTermination(10,TimeUnit.SECONDS);