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

   @Override
   public boolean retry(ITestResult result) {
     if (!result.isSuccess()) {
       if (count < maxCount) {
         count++;
         result.setStatus(ITestResult.SUCCESS);
         String message = Thread.currentThread().getName() + ": Error in Method Name: " + result.getName() + " ."+" Hence, Retrying "
             + (maxCount + 1 - count) + " more time";
         System.out.println(message);
         Reporter.log(message);
         return true;
       } else {
         result.setStatus(ITestResult.FAILURE);
       }
     }
     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{
   driver.get("https://www.google.co.in/");
   assertTrue(driver.getTitle().contains("Google"));

  }


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.