如何对在执行程序服务中运行的代码段进行单元测试,而不是在Thread.sleep(time)上等待 [英] How to unit test a code snippet running inside executor service, instead waiting on Thread.sleep(time)

查看:146
本文介绍了如何对在执行程序服务中运行的代码段进行单元测试,而不是在Thread.sleep(time)上等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对在执行程序服务中运行的代码进行单元测试? 就我而言,

How to unit test a code that is running in executor service? In my situation,

public void test() {
    Runnable R = new Runnable() {
        @Override
        public void run() {
            executeTask1();
            executeTask2();
        }
    };

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(R);
}

在进行单元测试时,我想对方法执行进行一些验证.

When I am unit testing, I would like to make some validations that method executes.

我正在执行程序服务中执行此操作,因为它执行一些网络操作.

I am executing this in an executor service, as it makes some network operations.

在单元测试中,我不得不等到该方法完成执行.有没有一种更好的方法可以代替等待Thread.sleep(500)了.

In my unit testing, I had to wait until this method finishes execution. Is there a better way I can do this, instead of waiting for Thread.sleep(500).

单元测试代码段:

@Test
public void testingTask() {
    mTestObject.test();
    final long threadSleepTime = 10000L;
    Thread.sleep(threadSleepTime);
    verify(abc, times(2))
            .acquireClient(a, b, c);
    verify(abd, times(1)).addCallback(callback);
}

注意:我正在将执行程序服务对象传递给此构造函数类. 我想知道是否有一种很好的测试方法,而不是等待睡眠时间.

Note: I am passing an executor service object into this constructor class. I would like to know if there is a good way of testing instead of waiting for sleep time.

推荐答案

您还可以自己实现一个ExecutorService,它将在同一线程中运行任务.例如:

You could also implement an ExecutorService yourself that will run the task in the same thread. For example:

public class CurrentThreadExecutor implements Executor {
    public void execute(Runnable r) {
        r.run();
    }
}

然后您可以从AbstractExecutorService继承并使用此实现.

And then you could inherit from AbstractExecutorService and use this implementation.

如果您使用的是Guava,另一种简单的方法是使用

If you're using Guava, another easy one is to use MoreExecutors.newDirectExecutorService() since that does the same thing without you having to create one yourself.

这篇关于如何对在执行程序服务中运行的代码段进行单元测试,而不是在Thread.sleep(time)上等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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