【问题标题】:ExecutorService doesn't execute Runnables in JUnit testsExecutorService 在 JUnit 测试中不执行 Runnables
【发布时间】:2018-05-10 13:02:55
【问题描述】:

我有一个要测试的执行器服务。

我有几个需要调用的任务(Runnables),然后调用 wait() 并在几秒钟后调用一个虚拟计时器 notify()

我这样做是为了检查所有任务是否在一段时间后按顺序执行。

问题是我的 Runnable 的 run() 方法根本没有被调用。我设置了一个断点,代码执行没有到达。

在普通编码中它工作得很好。任务排队,它们调用 wait() 直到没有获得响应或触发超时,它们调用 notify() 并执行下一个任务。

问题出在我运行测试时。

对此有什么想法吗?

【问题讨论】:

  • 调试时,你是否使用了 Suspend VM / Suspend Thread..?您也可以分享您的代码以供参考。

标签: java android multithreading executorservice scheduledexecutorservice


【解决方案1】:

test 方法在其他线程命中waitnotify 之前退出时,可能会发生这种情况。

尝试调用:

executorService.shutdown();
try {
    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {

}

在退出test 方法之前。它将阻塞测试方法,直到所有Runnable 完成。

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 2018-02-09
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    相关资源
    最近更新 更多