開発者ドキュメント

JUnit – タイムアウトテスト

テストが定義された “タイムアウト”よりも長い時間がかかると、 `TestTimedOutException`がスローされ、テストは失敗しました。次の例を参照してください。


P.S JUnit 4.12

でテスト済み

1.タイムアウトの例

この `timeout`の例は、単一のテストメソッドにのみ適用されます。タイムアウト値はミリ秒です。

TimeoutTest.java

package com.mkyong;

import org.junit.Test;

public class TimeoutTest {

   //This test will always failed :)
    @Test(timeout = 1000)
    public void infinity() {
        while (true) ;
    }

   //This test can't run more than 5 seconds, else failed
    @Test(timeout = 5000)
    public void testSlowMethod() {
       //...
    }

}

このタイムアウトテストは、メソッドのパフォーマンスをテストするのに便利です。

2.グローバルタイムアウトルールの例

この例は、グローバルタイムアウトルールを作成する方法を示しています。このルールは、クラス内のすべてのテストメソッドに適用されます。

TimeoutTest.java

package com.mkyong;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

import java.util.concurrent.TimeUnit;

public class TimeoutRuleTest {

   //global timeout rule
    @Rule
    public Timeout globalTimeout = Timeout.seconds(1);

   //This test will be failed, because it will take more than 1 second to finish!
    @Test
    public void testSlowMethod1() throws InterruptedException {
       //...
        TimeUnit.SECONDS.sleep(5000);
    }

   //passed
    @Test
    public void testSlowMethod2() {
       //...
    }

}

上記の例では、 `testSlowMethod1()`と `testSlowMethod2()`の両方が1秒以内にテストを終了する必要があります。そうでなければ、テストは失敗します。

__P.Sルールは

@ Before`と

@ After`メソッドにも適用されます。

モバイルバージョンを終了