JUnit – Timeout Test
If a test is taking longer than a defined “timeout” to finish, a TestTimedOutException
will be thrown and the test marked failed. See the following example :
P.S Tested with JUnit 4.12
1. Timeout Example
This timeout
example only applies to a single test method. And the timeout value is in milliseconds.
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() {
//...
}
}
This timeout test is useful to test on the method performance.
2. Global Timeout Rule Example
This example shows you how to create a global timeout rule, this rule will apply to all the test methods in a class.
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() {
//...
}
}
In the above example, a global Timeout
rule is declared, both the testSlowMethod1()
and testSlowMethod2()
must finish the test within 1 second, else the test will be failed.
P.S The rule also applies on @Before
and @After
methods.
Note
All unit test should be fast, and this global timeout rule should be your best helper.
All unit test should be fast, and this global timeout rule should be your best helper.
It is giving me the error
The method seconds(int) is undefined for the type Timeout
I also have the error The method seconds(int) is undefined for the type Timeout