In TestNG, you can retry failed test cases automatically by implementing the IRetryAnalyzer
interface. This is useful when you want to re-execute flaky or intermittently failing tests a certain number of times before marking them as failed.
Steps to Retry Failed Test Cases in TestNG
Create a Retry Analyzer Class:
Implement the
IRetryAnalyzer
interface.Override the
retry()
method which returnstrue
if TestNG should retry the test.
- Attach Retry Analyzer to Test:
You can attach it directly using
@Test(retryAnalyzer = ...)
,
or apply it globally using anIAnnotationTransformer
.
Example 1: Basic Retry Analyzer with Retry Count = 3
RetryAnalyzer.java
import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class RetryAnalyzer implements IRetryAnalyzer { private int retryCount = 0; private static final int maxRetryCount = 3; @Override public boolean retry(ITestResult result) { if (retryCount < maxRetryCount) { System.out.println("Retrying test: " + result.getName() + " | Attempt: " + (retryCount + 1)); retryCount++; return true; } return false; } }
Example Test Class: TestRetryExample.java
import org.testng.Assert; import org.testng.annotations.Test; public class TestRetryExample { int attempt = 1; @Test(retryAnalyzer = RetryAnalyzer.class) public void testMethod() { System.out.println("Running test attempt: " + attempt); if (attempt < 3) { attempt++; Assert.fail("Failing the test intentionally"); } Assert.assertTrue(true); } }
Optional: Apply Retry Analyzer Globally
Instead of using @Test(retryAnalyzer = ...)
on each test, you can apply the retry logic globally using IAnnotationTransformer
.
RetryListener.java
import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class RetryListener implements IAnnotationTransformer { @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { annotation.setRetryAnalyzer(RetryAnalyzer.class); } }
testng.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="RetrySuite"> <listeners> <listener class-name="RetryListener"/> </listeners> <test name="RetryTest"> <classes> <class name="TestRetryExample"/> </classes> </test> </suite>
Important Points:
Component | Purpose |
---|---|
IRetryAnalyzer | Handles retry logic for a failed test |
retry() | Returns true if the test should be retried |
@Test(retryAnalyzer = ...) | Assigns retry logic to a test |
IAnnotationTransformer | Optional global retry setup via listener |
No comments:
Post a Comment