我是通過一個ScheduledExecutorService
作爲合作者的單位TDDing。 這個單位有一個start
方法,基本上啓動執行者的任務,我現在想寫驅動stop
方法的測試,因爲我知道,由於沒有人會調用ScheduledExecutorService.shutdown
線程將掛起(默認情況下不是守護進程線程)。如何編寫自未調用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();
}
} }
你爲什麼不嘲笑安排的執行器服務,並詢問模擬它是否被調用?我不確定我瞭解你的代碼的描述。爲什麼不自己編寫代碼,期望你期望它做什麼以及它做什麼呢? –
@JBNizet我試圖遵循「只嘲弄你自己」的規則,所以我不想嘲笑執行者。我會在幾分鐘內發佈代碼的簡化版本。謝謝 – Ittai
@JBNizet我已經添加了一個代碼示例。謝謝。 – Ittai