In Selenium test automation using TestNG, we can rerun failed test cases automatically by implementing a custom RetryAnalyzer. This is especially useful for handling flaky or intermittent test failures.
The following example demonstrates how to rerun a failed test case up to 2 times by using the IRetryAnalyzer interface.
RetryAnalyzer Class (Handles Retry Logic)
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private static final int maxRetryCount = 2; // Retry 2 times
@Override
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true; // Retry the test
}
return false; // Do not retry
}
}
Sample Test Class Using RetryAnalyzer
We can attach the RetryAnalyzer to individual test methods using the @Test annotation.
import org.testng.annotations.Test;
public class SampleTest {
@Test(retryAnalyzer = RetryAnalyzer.class)
public void test1() {
System.out.println("Running test1");
Assert.fail("Test failed"); // Fails intentionally
}
}
✅ Summary
- The
RetryAnalyzerclass controls how many times a failed test should be retried. - You can apply it at the test method level using
@Test(retryAnalyzer = RetryAnalyzer.class). - This approach is ideal for handling non-deterministic failures caused by UI loading delays, network issues, etc.