How to unit test a code snippet running inside executor service, instead waiting on Thread.sleep(time)

samuel koduri picture samuel koduri · Sep 24, 2017 · Viewed 20.1k times · Source

How to unit test a code that is running in executor service? In my situation,

public void test() {
    Runnable R = new Runnable() {
        @Override
        public void run() {
            executeTask1();
            executeTask2();
        }
    };

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(R);
}

When I am unit testing, I would like to make some validations that method executes.

I am executing this in an executor service, as it makes some network operations.

In my unit testing, I had to wait until this method finishes execution. Is there a better way I can do this, instead of waiting for Thread.sleep(500).

Unit testing code snippet:

@Test
public void testingTask() {
    mTestObject.test();
    final long threadSleepTime = 10000L;
    Thread.sleep(threadSleepTime);
    verify(abc, times(2))
            .acquireClient(a, b, c);
    verify(abd, times(1)).addCallback(callback);
}

Note: I am passing an executor service object into this constructor class. I would like to know if there is a good way of testing instead of waiting for sleep time.

Answer

claudio picture claudio · May 31, 2018

You could also implement an ExecutorService yourself that will run the task in the same thread. For example:

public class CurrentThreadExecutor implements Executor {
    public void execute(Runnable r) {
        r.run();
    }
}

And then you could inherit from AbstractExecutorService and use this implementation.

If you're using Guava, another easy one is to use MoreExecutors.newDirectExecutorService() since that does the same thing without you having to create one yourself.