We can specify a timeout for our TestNG tests. This can be done in the test class by setting timeOut
property of @Test
annotation.
When the test methods doesn’t finish in the specified timeout, org.testng.internal.thread.ThreadTimeoutException
is thrown and method is marked as failed.
TestNG Timeout @Test Example
Here is a simple class where timeout is specified for the test methods.
package com.journaldev.timeout;
import org.testng.annotations.Test;
public class TimeoutExample {
@Test(timeOut = 300)
public void foo() throws InterruptedException {
Thread.sleep(200);
System.out.println("foo method executed");
}
@Test(timeOut = 300)
public void bar() throws InterruptedException {
Thread.sleep(400);
System.out.println("bar method executed");
}
}
When we execute above class, we get following output.
[RemoteTestNG] detected TestNG version 6.14.3
foo method executed
PASSED: foo
FAILED: bar
org.testng.internal.thread.ThreadTimeoutException: Method com.journaldev.timeout.TimeoutExample.bar() didn't finish within the time-out 300
TestNG XML Timeout Example
We can specify the timeout value in XML suite as well, both at suite level and test level. If we have a timeout specified at both places, then the lowest value is considered for the test methods execution.
Let’s look at this with a simple TestNG XML suite example.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="TestNGXMLTest Test Suite" time-out="500">
<test name="TestNGXMLTest Test 1" verbose="2" time-out="300">
<classes>
<class name="com.journaldev.timeout.TimeoutExample" />
</classes>
</test>
</suite>
Notice that suite level timeout is 500 ms whereas test level timeout is 300 ms. We get the following output when it’s executed.
foo method executed
PASSED: foo
FAILED: bar
org.testng.internal.thread.ThreadTimeoutException: Method com.journaldev.timeout.TimeoutExample.bar() didn't finish within the time-out 300
Change the suite level timeout to 300 ms and test level timeout to 500 ms. We will still get the same exception as above, this means that lowest value of timeout is being considered for execution.
That’s all for a quick brief on TestNG timeout configurations.