How does one unit test that a new thread was spawned for a Runnable task when using an ExecutorService?
Basically, I have a static thread pool for my application.
public static final ExecutorService executorService = Executors.newCachedThreadPool();
I'd like to use this thread pool for the my unit tests, rather than mocking one out or injecting a new thread pool, since different thread pools can dramatically alter the behavior of my application (fixed vs. cached vs. scheduled, etc); I want to ensure that I test the application's behavior with its run-time thread pool.
Cached thread pool seems to work best for me. The problem is that since it's static and the threads are cached for 60 seconds, only the first test will actually spawn a new thread in the pool, while subsequent tests reuse that thread.
Unit test code:
public void testDoCallExecutesTaskInAnotherThread() { final Client client = this.createClient(); final ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) client.getExecutorService(); // gets the static thread pool final int initPoolSize = threadPoolExecutor.getPoolSize(); final Response response = client.doCall(); Assert.assertEquals(initPoolSize + 1, threadPoolExecutor.getPoolSize()); }
Advice on how to get this working, or another approach altogether would be appreciated.