简体   繁体   English

我如何对 Java Executor 服务进行单元测试?

[英]How can I unit test Java Executor service?

I have created ExecutorService bean and injected it as dependency, to close it I have copied code from Official website, and wrote jUnit to call method directly, but now it shows coverage for first line only我已经创建了 ExecutorService bean 并将其作为依赖项注入,为了关闭它我从官方网站复制了代码,并编写了 jUnit 来直接调用方法,但现在它仅显示第一行的覆盖率

@Override
public void onApplicationEvent(ContextClosedEvent event) {
    execService.shutdown();
    try {
        if (!execService.awaitTermination(60, TimeUnit.SECONDS)) {
            execService.shutdownNow();
            if (!execService.awaitTermination(60, TimeUnit.SECONDS))
                log.error("Pool did not terminate");
        }
        log.info("ExecutorService shutdown hook called! " + execService);
    } catch (InterruptedException ie) {
        execService.shutdownNow();
        Thread.currentThread().interrupt();
    }

}

Please suggest a way to test it using jUnit and Mockito or powerMockito.请建议一种使用 jUnit 和 Mockito 或 powerMockito 进行测试的方法。 I am not sure how to cover execService.awaitTermination and another execService.shutdownNow()我不确定如何涵盖 execService.awaitTermination 和另一个 execService.shutdownNow()

To test the awaitTermination() code and beyond you could add a task to the executor service that fails to check Thread.interrupted() or Thread.isInterrupted() and then you make the task run forever (like an infinite loop).要测试 awaitTermination() 代码及其他代码,您可以向无法检查 Thread.interrupted() 或 Thread.isInterrupted() 的执行程序服务添加任务,然后让任务永远运行(如无限循环)。

That should make all the error code pass.那应该使所有错误代码通过。

The only problem is that your test will take 2 minutes to execute.唯一的问题是您的测试需要 2 分钟才能执行。 Which is pretty bad.这很糟糕。 So maybe instead of hardcoding the 60 seconds you could enter some way of making it only wait 1 millisecond.因此,也许您可以输入某种方式使其仅等待 1 毫秒,而不是对 60 秒进行硬编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM