0

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.

Juan Cruz Soler
  • 8,172
  • 5
  • 41
  • 44
Sumalatha Abhishek
  • 641
  • 1
  • 8
  • 16
  • 1
    Based on the [API](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-), a task is executed *some time in the future*. The unit test is trying to `verify` when some of the tasks have not yet completed. [This](https://stackoverflow.com/questions/1250643/how-to-wait-for-all-threads-to-finish-using-executorservice) might help. – Andrew S Oct 31 '17 at 18:32

1 Answers1

3

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