[英]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? 在使用ExecutorService时,一个单元如何测试为Runnable任务生成新线程?
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.
问题是因为它是静态的并且线程被缓存了60秒,所以只有第一个测试实际上会在池中产生一个新线程,而后续测试会重用该线程。
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
:
ThreadFactory mock = new CustomObservableThreadFactory();
ExecutorService executorService = Executors.newCachedThreadPool(mock);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.