我正在通过一个ScheduledExecutorService
作为合作者的单位进行 TDD。这个单元有一个start
方法,它基本上用任务启动执行程序,我现在想编写驱动该stop
方法的测试,因为我知道没有人会调用ScheduledExecutorService.shutdown
线程将挂起(默认情况下不是守护线程)。
我想通过@Test(timeout = 5000L)
并使用实际的执行程序服务(而不是确定性服务)来构建单元,但我面临的问题是由于某种原因测试没有挂起。
我认为,不确定,这与 Intellij/Junit 混合调用system.exit
和杀死“我的”jvm 有关。
在我用一种main
方法编写的手动“测试”中,我可以验证在不调用该shutdown
方法的情况下系统确实卡住了。
关于如何测试这个的任何想法?
谢谢
更新
我整理了一个小代码示例来说明问题:
public class SomethingTest {
@Test(timeout = 5000L)
public void shouldStopExecutorServiceWhenStopped2() throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Something cds = new Something(scheduler);
cds.start();
Thread.sleep(2000); //this is to be pretty sure that the scheduling started since I'm not certain the thread will deterministically block otherwise
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Something cds = new Something(scheduler);
cds.start();
Thread.sleep(2000); //this is to be pretty sure that the scheduling started since I'm not certain the thread will deterministically block otherwise
cds.stop(); //comment this out to see that it hangs if shutdown isn't called
}
public static class Something {
private final ScheduledExecutorService scheduler;
public Something(ScheduledExecutorService scheduler) {
this.scheduler = scheduler;
}
public void start() {
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("did something really important over time");
}
}, 0, 5, TimeUnit.SECONDS);
}
public void stop() {
scheduler.shutdownNow();
}
} }