0

をコラボレーターとしているユニットで 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();
    }
} }
4

2 に答える 2

0

私がやろうと思っていること (今は時間がありません) は、終了する前にデーモン以外のスレッドが実行されているかどうかをチェックする Timeout ルールに非常によく似た JUnit TestRule を作成することです。
基本的に、この疑似ブロックの後にシステムがハングしないことを確認したいので、デーモン以外のスレッドが実行されている場合はテストを失敗させたいと思いnew unit();unit.start;unit.stopます。しばらくの間 (テストを決定論的にし、実際にそのスレッドを閉じるオプションを jvm に与えるための入力タイムアウト)。

于 2013-07-15T07:46:57.553 に答える