Retry failed test automatically up to 2 times
Preconditions (3)
✅ Expected Result: The failed test is retried automatically up to 2 times before final failure is reported
import org.testng.IRetryAnalyzer; import org.testng.ITestResult; import org.testng.annotations.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import static org.testng.Assert.assertTrue; public class RetryAnalyzer implements IRetryAnalyzer { private int retryCount = 0; private static final int maxRetryCount = 2; @Override public boolean retry(ITestResult result) { if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } } public class SampleTest { WebDriver driver; @Test(retryAnalyzer = RetryAnalyzer.class) public void testGoogleSearch() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.get("https://www.google.com"); // Intentionally failing assertion to demonstrate retry boolean isSearchBoxPresent = driver.findElements(By.name("q")).size() > 0; assertTrue(isSearchBoxPresent, "Search box should be present on Google homepage"); driver.quit(); } }
The RetryAnalyzer class implements IRetryAnalyzer interface from TestNG. It overrides the retry method to retry the test up to 2 times if it fails.
The SampleTest class contains a test method testGoogleSearch annotated with @Test and linked to RetryAnalyzer via retryAnalyzer attribute.
When the test fails, TestNG calls retry method. If retry count is less than max, it returns true to rerun the test. Otherwise, it stops retrying.
This setup helps automatically rerun flaky tests to reduce false negatives.
Now add data-driven testing with 3 different search keywords and retry on failure
RetryAnalyzer in Selenium Java testing?retry(ITestResult result) method to decide if a test should rerun.onTestStart(), beforeMethod(), and afterTest() belong to other TestNG listeners or annotations, not RetryAnalyzer.public class Retry implements IRetryAnalyzer {
private int count = 0;
private static final int maxRetryCount = 2;
public boolean retry(ITestResult result) {
if (count < maxRetryCount) {
count++;
return true;
}
return false;
}
}public class Retry implements IRetryAnalyzer {
private int count = 0;
private static final int maxRetryCount = 3;
public boolean retry(ITestResult result) {
if (count <= maxRetryCount) {
count++;
return true;
}
return false;
}
}count <= maxRetryCount allows one extra retry than intended because count starts at 0.count < maxRetryCount ensures retries happen exactly maxRetryCount times.TimeoutException. Which approach is correct?result.getThrowable() is instance of TimeoutException. Return true to retry only in that case.Pass the test and this pattern moves unknown