Why failed test cases Re-Run in Selenium again?
- While working with internal applications, you can see that your test is unnecessarily unsuccessful at any points and if you run the same test again, it passes without any changes so in this case we re-run our test again.
- Sometimes case fail due to minor issue’s so to cross verify exception exist on not exist in Selenium script that time we can re-run selenium script.
There are several reasons for the failure of the test:
- Due to network problem.
- Reasons for Application Downtime.
- Due to load issue and etc.
If the test fails because of above reasons we will re-run then again. Instead of running test case manually we can ask TestNG to execute the failed test cases again for any number of times and check for the updated results.
But if the script is failing due to Xpath and some legitimate reason, then you have to maintain your script to work again.
How to retry failed test case in Selenium?
- If you thought it is very difficult to run the failed script automatically again then it is not. We need to write a separate Java class which will take care of the failure if you run the test.
- We will use an
IRetryAnalyzerinterface which is part of TestNG and we need to override the method of retrying.
Step 1:
Create a class with rerun logic:
package retryLogic;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class Retry implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 2;
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true;
}
return false;
}
}
Step 2:
Use annotation in your test program:
If Test case fail then we use retryAnalyzer annotation within the @Test with the help of Retry.class re-run selenium script.
package retryLogic;
import org.testng.Assert;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
import org.testng.annotations.Test;
public class Retry implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 2;
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true;
}
return false;
}
@Test(retryAnalyzer = Retry.class)
public void testPass() {
// ListenerTest Pass
Assert.assertEquals("sandeep", "sandeep");
}
@Test(retryAnalyzer = Retry.class)
public void testFail() {
// ListenerTest fails
Assert.assertEquals("hello", "World");
}
}