Timeout test in JUnit

In this blogpost, we are going to have a look at timeout feature provided by JUnit API.

If a test takes more than expected time to finish, then JUnit will automatically mark the test as FAILED with TestTimedOutException.

In order to give timeout to a particular test, timeout attribute is set along with @Test annotation. Timeout is in milliseconds.


public void test(){}}

Let us have a look at the code snippet to see this in action.

We have given 2000 milliseconds as a timeout value, meaning if the test method does not complete its execution within 2 seconds, JUnit will mark it as FAILED, and throw TestTimedOutException.

import static org.junit.Assert.*;

import org.junit.Test;

public class TimeoutClass {

@Test(timeout = 2000)
public void test() throws InterruptedException {
               System.out.println(“Inside test method…”);
               System.out.println(“Waiting for 5 seconds…”);


Thread.sleep(5000); statement in the test  method forces the method to take 5 seconds to finish the execution, the test method will be marked FAILED by JUnit.


Hope it works for you!!

Cheers 🙂


#testtimedoutexception, #timeout-test-in-junit