をコラボレーターとしているユニットで TDD を行っていScheduledExecutorService
ます。このユニットには、start
基本的にタスクでエグゼキューターを開始するメソッドがあり、メソッドを駆動するテストを書きたいと思います。誰もスレッドstop
を呼び出さないScheduledExecutorService.shutdown
とハングすることがわかっているからです (デフォルトではデーモン スレッドではありません)。
実際のエグゼキューター サービス (決定論的なものではない) を使用してユニットを構築することでこれを実行したかった@Test(timeout = 5000L)
のですが、直面している問題は、何らかの理由でテストがハングしないことです。
確かではありませんが、これは Intellij/Junit mix 呼び出しsystem.exit
と「my」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();
}
} }