Restart failed test case automatically in TestNG/Selenium

MostWanted picture MostWanted · Jan 3, 2012 · Viewed 25k times · Source

I am using Selenium webdriver, in Java with TestNG to run an X amount of test cases.

What I would like, is for any test case to automatically restart (either from starting or from point of failure), as soon as it fails.

I know TestNG framework has the following method

@Override
  public void onTestFailure(ITestResult tr) {
    log("F");
  }

but I do not know how to find out which testcase it was and then how would I restart it.

Answer

gorbysbm picture gorbysbm · Dec 17, 2013

I wanted to see an example with actual code in it and found it here: Restarting Test immediately with TestNg

Observe how the below tests will each be re-run once as soon as the failure happens.

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() {
        Assert.assertEquals("james", "JamesFail"); // ListenerTest fails
    }

    @Test(retryAnalyzer = Retry.class)
    public void testGenY() {
        Assert.assertEquals("hello", "World"); // ListenerTest fails

    }
}