TestNG is a wonderful Test framework. It provides lot of features that can help us make robust and maintainable frameworks. In this chapter we will learn How to Retry Failed Tests in TestNG.
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryAnalyzer implements IRetryAnalyzer {
int counter = 0;
int retryLimit = 2;
@Override
public boolean retry(ITestResult result) {
if(counter < retryLimit)
{
counter++;
return true;
}
return false;
}
}
There are two ways to include retry analyser in your tests
- By specifying retryAnalyzer value in the @Test annotation
- By adding Retry analyser during run time by implementing on the of the Listener interfaces
public class Test001 {
@Test(retryAnalyzer = Tests.RetryAnalyzer.class)
public void Test1()
{
Assert.assertEquals(false, true);
}
@Test
public void Test2()
{
Assert.assertEquals(false, true);
}
}
Here we have two tests and one test is specifying which class to use
as retry analyser. If we run this test we will get following results

You can see that Test1 was run 4 times and its been marked failed only at the last run. It was run 4 times because of the retry analyser. However, looking at Test2 we can see that it is run only once. This is obvious because we never specified a retryAnalyzer for Test2

You can see that Test1 was run 4 times and its been marked failed only at the last run. It was run 4 times because of the retry analyser. However, looking at Test2 we can see that it is run only once. This is obvious because we never specified a retryAnalyzer for Test2
package Tests;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
public class AnnotationTransformer implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
annotation.setRetryAnalyzer(RetryAnalyzer.class);
}
}
Once we have the implementation of IAnnotationTransformer, we just need to add it as a listener in the testng run xml. Like this
Now we don’t have to specify the retryAnalyzer attribute in the @Test annotation. Updated tests will look like this
import org.testng.Assert;
import org.testng.annotations.Test;
public class Test001 {
@Test
public void Test1()
{
Assert.assertEquals(false, true);
}
@Test
public void Test2()
{
Assert.assertEquals(false, true);
}
}
https://www.toolsqa.com/selenium-webdriver/retry-failed-tests-testng/
No comments:
Post a Comment