Testing timeouts with JUnit 4
Overview
In this post, we will discuss the timeout attribute of the @Test method annotation. Testing timeouts in JUnit 4 we need to use the attribute timeout in the @Test(timeout=<value>) annotation. There are other ways to test if the method executes within the specified time, but we will stick to the method-level ( per-test) annotation-based approach here.
Let’s consider that we gonna test whether a method executes within the specified time or not.
Sample Listing
package com.testingdocs.sample;
import org.junit.Test;
public class JUnit4TestClass {
/* set timeout 3 secs for the method */
@Test(timeout=3000)
public void timeOutTest() throws InterruptedException {
/* Simulate a task that takes 2 secs.
* 2 < 3 so this method should pass */
Thread.sleep(2000);
}
}
In the annotation, we have specified 3 secs timeout and simulated a method that takes only 2 secs to complete. Hence, the method should pass in the test result.

Failure method that exceeds timeout
Now, let us simulate a test failure. We would specify a timeout less than that of the method completion time and check. We have specified timeout as 2 secs and method task 3 secs. The method takes longer tom complete than the timeout.
package com.testingdocs.sample;
import org.junit.Test;
public class JUnit4TestClass {
/* set timeout 3 secs for the method */
@Test(timeout=2000)
public void timeOutTest() throws InterruptedException {
/* Simulate a task that takes 3 secs.
* 2 (timeout) < 3 so this method should be marked as
* a failure */
Thread.sleep(3000);
}
}

Class level
To apply the timeout to all the methods you can create a rule as shown below:
package com.testingdocs.sample;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.concurrent.TimeUnit;
public class JUnit4TestClass {
@Rule
public Timeout timeout = new Timeout(3000);
@Test
public void timeOutTest1() throws InterruptedException {
Thread.sleep(4000);
}
@Test
public void timeOutTest2() throws InterruptedException {
Thread.sleep(1000);
}
}