How to unit test that ExecutorService spawns new thread for task?
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.getExecutorSe开发者_运维技巧rvice(); // 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.
Mock the ThreadFactory
:
ThreadFactory mock = new CustomObservableThreadFactory();
ExecutorService executorService = Executors.newCachedThreadPool(mock);
- Inject the ExecutorService into the class under test as usual
- But use a custom ThreadFactory for creating the cached ThreadPool: The ThreadFactory will be called whenever a new Thread is to be called. You can then trace these instantiations as you like, e.g.with a listener or counter.
精彩评论