如何单元测试ExecutorService产生任务的新线程? [英] How to unit test that ExecutorService spawns new thread for task?

查看:1380
本文介绍了如何单元测试ExecutorService产生任务的新线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用ExecutorService时,一个单元如何测试一个新的线程是否为一个Runnable任务产生?

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.

缓存线程池似乎对我最好的工作。问题是,因为它是静态的,线程被缓存60秒,只有第一个测试将实际上在池中产生一个新的线程,而后续的测试重用该线程。

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.

单元测试代码:


    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.

推荐答案

模拟 ThreadFactory

  ThreadFactory mock = new CustomObservableThreadFactory();
  ExecutorService executorService = Executors.newCachedThreadPool(mock);




  1. 将ExecutorService像往常一样注入到测试类中

  2. 但是使用自定义ThreadFactory 创建缓存的ThreadPool:
    当一个新的Thread被调用时,ThreadFactory将被调用。
    然后,您可以随意跟踪这些实例化,例如使用侦听器或计数器。

  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, e.g.with a listener or counter.

这篇关于如何单元测试ExecutorService产生任务的新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆