How to Re-run the failed test cases automatically in selenium with testng

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 RetryAnalyzer class 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.
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x