第77回 JUnit4 その5
引き続き「JUnit4」について学んでいきます。
今回はJUnit4におけるテストのタイムアウト処理について学びます。
JUnit4では、テストメソッドのタイムアウト時間を設定できます。
設定した時間内にテストメソッドが終了しなかったら、テスト失敗となります。
設定方法は例外のテストと同様に、@Testで指定します。
例えば、タイムアウト時間を10ミリ秒に設定する場合、@Test(timeout = 10)とします。
では、実際にタイムアウト処理をテストしてみましょう。
最初のテストはThreadクラスのsleepメソッドによりタイムアウトさせています。
public class Sample { public static Object returnNull() throws InterruptedException { Thread.sleep(100); return null; } public static void throwRuntimeException() { throw new RuntimeException(); } }
import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.JUnitCore; public class SampleTest { public static void main(String[] args) { JUnitCore.main(SampleTest.class.getName()); } @Test(timeout = 10) public void returnNull() throws InterruptedException { assertNull(Sample.returnNull()); } @Test(timeout = 0, expected = RuntimeException.class) public void throwRuntimeException() { Sample.throwRuntimeException(); } }
java.lang.Exception: test timed out after 10 millisecondsと表示され、タイムアウトによるテスト失敗が確認できますね。