简体   繁体   中英

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

@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. I am not sure how to cover execService.awaitTermination and another 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).

That should make all the error code pass.

The only problem is that your test will take 2 minutes to execute. Which is pretty bad. So maybe instead of hardcoding the 60 seconds you could enter some way of making it only wait 1 millisecond.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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