Sunday, 28 September 2014

Re-Run the failed Test Scripts in WebDriver using TestNG

Re-running the failed Test Cases in WebDriver has become  a Business Requirement now a days.
Because some times a test case fails at first due to network latency, or any other reason.

So, if we want to re-run the failed test cases automatically we need to write some Java code as follows:

public class RerunFailedTestScripts implements IRetryAnalyzer{

 private int count = 0;
   private int maxCount = 1; // Currently Failed Test Cases will run 1 time after failure

   public boolean retry(ITestResult result) {
     if (!result.isSuccess()) {
       if (count < maxCount) {
         String message = Thread.currentThread().getName() + ": Error in Method Name: " + result.getName() + " ."+" Hence, Retrying "
             + (maxCount + 1 - count) + " more time";
         return true;
       } else {
     return false;

Here, we are using IRetryAnalyzer , Interface of TestNG to implement to be able to have a chance to retry a failed test. Also, you can configure in 'maxCount' that how many times to run the failed Test Cases.

Then, to re-run the test cases which you want to write the following in the Test Script class :

  @Test(groups={"sanity"},alwaysRun=true,priority = 1, retryAnalyzer=RerunFailedTestScripts.class)
 public class OpenGoogle
  public void testOpenGoogle() throws InterruptedException{


Here, we are calling the above class that we made in @Test Annotation in the Test Script Class.

And You are done with the Re-Run Failed Test Cases Framework.