简体   繁体   中英

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.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.

Mock the ThreadFactory :

  ThreadFactory mock = new CustomObservableThreadFactory();
  ExecutorService executorService = Executors.newCachedThreadPool(mock);
  1. Inject the ExecutorService into the class under test as usual
  2. 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, egwith a listener or counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM