IRetryAnalyzer to Retry / Re-Run Failed Test in TestNG:
Why failed test cases Re-Run in Selenium again?
- While working with internal applications, you can see that your test is unnecessarily unsuccessful at different points and once you run the same test again, it passes without any changes.
- Sometimes case fail due to minor issue’s so to cross verify exception exist on not exist in Selenium script that time we 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.
- 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 re-run failed test case in Selenium?
- It seems very difficult to run the script automatically again but 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 IRetryAnalyzer interface which is part of TestNG and we need to override the method of retrying.
Step 1: Create a class with rerun logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class Retry implements IRetryAnalyzer { private int retryCount = 0; private int maxRetryCount = 1; 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 using retryAnalyzer annotation use within the @Test then with the help of Retry.class re-run selenium script.
1 2 3 4 5 6 7 8 | // Using retryAnalyzer able to rerun particular method @Test(retryAnalyzer = Retry.class) public void testGenX() { // ListenerTest Fail Assert.assertEquals("sandeep", "sandy"); } |
Example: IRetryAnalyzer to Retry / Re-Run Failed Test in TestNG.
- with the help of assertEquals verify pass / fail result of existing test case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package package_name; 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 = 1; public boolean retry(ITestResult result) { if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } @Test(retryAnalyzer = Retry.class) public void testGenX() { // ListenerTest Pass Assert.assertEquals("sandeep", "sandeep"); } @Test(retryAnalyzer = Retry.class) public void testGenY() { // ListenerTest fails Assert.assertEquals("hello", "World"); } } |
Output:
1 2 3 4 5 | PASSED: testGenX FAILED: testGenY SKIPPED: testGenY |
Note: testGenY test case fail due to rerun. With the help of Assertions we can decide status of existing class.
How to Retry Failed Tests in TestNG Automation Framework and How To Run Failed Test Cases Using TestNG In Selenium WebDriver