How to define Test Timeout in TestNG

Abhishek Dhoundiyal
2 min readFeb 26, 2023

--

TestNG allows us to set a timeout period for a test to get execute completely.

Timeout can be configured at two levels:

  • Suite level — This will be applicable for all the tests present in the TestNG test suite.
  • Test level — This will be applicable for the test method where we have define it and will override the timeout period if configured at the suite level.

Let’s understand how we can practically configure this:

1) Timeout at Test Level

This can be done in the test class by setting timeOut property of @Test annotation.

In below test, we have two test methods i.e. dummyTest1() and dummyTest2(). dummyTest1() will take 200ms to execute whereas dummyTest2() will take 300ms to execute.

We have define the TestNG test timeout of 100ms for every test.

Note: We have used Thread.sleep() method to demonstrate the timeout scenario.

Code:

import org.testng.annotations.Test;

public class TestNGTimeoutExample {

@Test(timeOut = 100)
public void dummyTest1() throws InterruptedException {
Thread.sleep(200);
System.out.println("Dummy method 1");
}

@Test(timeOut = 100)
public void dummyTest2() throws InterruptedException {
Thread.sleep(300);
System.out.println("Dummy method 2");
}

}

Output:

Exception: ThreadTimeoutException
Message:
1) dummyTest1() didn’t finish within the time-out 100
2) dummyTest2() didn’t finish within the time-out 100

2. Test Timeout at Suite Level

In below test, we have two test methods i.e. dummyTest1() and dummyTest2(). dummyTest1() will take 200ms to execute whereas dummyTest2() will take 300ms to execute.

Again, We have used Thread.sleep() method to demonstrate the timeout scenario.

Code:

public class TestNGTimeoutExample {

@Test()
public void dummyTest1() throws InterruptedException {
Thread.sleep(200);
System.out.println("Dummy method 1");
}
@Test()
public void dummyTest2() throws InterruptedException {
Thread.sleep(300);
System.out.println("Dummy method 2");
}

}

TestNG.xml

<suite name="TestNG Timeout test Suite" time-out="100" verbose="2" >
<test name="Testing TestNG Suite Level Timeout" >
<classes>
<class name="com.express.TestNGTimeoutExample" />
</classes>
</test>
</suite>

Output:

Conclusion:

When the test methods doesn’t get completed in the specified timeout, org.testng.internal.thread.ThreadTimeoutException exception is thrown and method will be marked as failed (as shown above).

--

--