Failing a TestNG Test on Timeout
Use the timeOut attribute in @Test to set an upper bound on how long the test may run (in milliseconds). If the test takes longer, TestNG marks it as FAILED with an interrupted exception.
Basic example:
Java
import org.testng.annotations.Test;
public class TimeoutTest {
@Test(timeOut = 1000) // Test must complete within 1000ms (1 second)
public void timeOutTest() throws InterruptedException {
// Sleep for 2 seconds — will cause timeout failure
Thread.sleep(2000);
System.out.println("Will throw Timeout exception!");
}
}
Test that passes within timeout:
Java
@Test(timeOut = 5000) // 5 seconds max
public void quickTest() throws InterruptedException {
Thread.sleep(1000); // Only 1 second — passes fine
System.out.println("Test completed within timeout");
}
Practical use in Selenium — page load timeout:
Java
@Test(timeOut = 10000) // 10 seconds
public void verifyPageLoad() {
driver.get("https://example.com");
// If page takes more than 10 seconds to load and assertions run, test fails
Assert.assertEquals(driver.getTitle(), "Example Domain");
}
Timeout for detecting stuck tests:
Java
@Test(timeOut = 30000) // 30 seconds
public void loginFlowTest() {
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("loginBtn")).click();
// If login hangs indefinitely, this will fail at 30s
wait.until(ExpectedConditions.titleIs("Dashboard"));
}
timeOut vs WebDriverWait:
| Feature | @Test(timeOut) | WebDriverWait |
|---|---|---|
| Scope | Entire test method | Specific element wait |
| Action on timeout | Test FAILED | TimeoutException thrown |
| Use case | Overall test duration cap | Wait for specific condition |
Key points:
- ✓Value is in milliseconds
- ✓Test is interrupted and marked
FAILEDif it exceeds the limit - ✓Use to prevent tests from hanging indefinitely in CI pipelines
