LoginSignup
1
1

More than 5 years have passed since last update.

JUnit での @Rule を使ったタイムアウト指定はテストクラスのコンストラクタで上書きできる

Posted at

JUnit を使ったテストで, テストに関するルールが基底クラスで設定されているとします.

TestProperty.java
public class TestProperty {
    @Rule
    public Timeout timeout = new Timeout(10000);
    // その他設定
}
SomethingTest1.java
public class SomethingTest1 extends TestProperty {
    @Test
    public void 早く終わらなければならないテスト() throws Exception {
        // ...
    }
}
SomethingTest2.java
public class SomethingTest2 extends TestProperty {
    @Test
    public void 時間がかかりそうなテスト() throws Exception {
        // ...
    }
}

そもそもこのようなテスト設計はどうなのかという問題は置いといて, とあるテストクラスだけタイムアウト指定を変更したい場合, テストクラスのコンストラクタで設定を上書きできます.

 public class SomethingTest1 extends TestProperty {
+    public SomethingTest1() {
+        super();
+        timeout = new Timeout(1);
+    }
     @Test
     public void 早く終わらなければならないテスト() throws Exception {
         // ...
     }
 }
 public class SomethingTest2 extends TestProperty {
+    public SomethingTest2() {
+        super();
+        timeout = new Timeout(100000);
+    }
     @Test
     public void 時間がかかりそうなテスト() throws Exception {
         // ...
     }
 }

次のような指定は無効らしいです.

SomethingTest1.java
public class SomethingTest1 extends TestProperty {
    @Before
    public void setup() {
        timeout = new Timeout(1);  // <- 無効. すでにtimeout設定が読まれている
    }
    @Test(timeout = 1)  // <- 無効. @Ruleが優先
    public void 早く終わらなければならないテスト() throws Exception {
        // ...
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1