How to define Test Timeout in TestNG

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:

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:

TestNG.xml

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).

Geek Culture

Proud to geek out. Follow to join our +1.5M monthly readers.