【问题标题】:JUnit testing with threads - testing executor behaviour使用线程的 JUnit 测试 - 测试执行程序的行为
【发布时间】:2013-11-26 10:16:36
【问题描述】:

考虑这个测试类,如果你运行 main 方法,该过程将在 5 分钟内不会完成,如果你运行测试它会立即成功。是否有任何推荐的方法来验证 Executor 行为?我预计测试也不会在 5 分钟内完成。

我遇到的具体问题是通过Executors.html#newScheduledThreadPool(int)创建一个ScheduledExecutorService,安排一个未来然后取消该未来不会终止底层Executor,因为默认RemoveOnCancelPolicy是等待取消的未来在终止之前安排。我正在通过公开正在使用的ScheduledThreadPoolExecutor 来解决这个问题,但我更愿意将其封装在我的实现中。

public class TestExecutor {

    @Test public void executorThatIsNotShutdown() {
        main(null);
    }

    public static void main(final String[] args) {
        final ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
        ex.schedule(new Runnable() {
            @Override
            public void run() {
            }
        }, 5, TimeUnit.MINUTES);
        ex.shutdown();
        System.out.println(ex.toString());
    }
}

【问题讨论】:

    标签: java multithreading junit


    【解决方案1】:

    在测试方法中提交/安排您的任务后尝试使用此代码:

    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);
    

    所以测试线程将被阻塞,直到所有任务都完成执行或发生超时

    【讨论】:

    • 我对等待执行程序终止并不感兴趣,我正在尝试测试它是否有。这很难做到,因为 JUnit 跑步者似乎要为我杀死 Executor。
    【解决方案2】:

    您需要添加以下代码以使您的主线程等待一段时间,直到您的 Executorsthread 完成其操作

    public static void main(final String[] args) {
        final ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
        ex.schedule(new Runnable() {
            @Override
            public void run() {
            }
        }, 5, TimeUnit.MINUTES);
        System.out.println(ex.toString());
       Thread.sleep('enter the time duration , so that your executor will finish its operation');
    }
    

    编辑:- 你可以试试另一种方法。 我有同样的问题,我把 thread.sleep() 放在实际测试方法之前

    @Before (method)
    Thread.sleep(mill secs);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2020-03-25
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多