This test sometimes fails randomly. The retry analyzer will retry it up to 2 times if it fails.
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.Test;
import org.testng.IRetryAnalyzer;
public class RetryAnalyzer implements IRetryAnalyzer {
private int count = 0;
private static final int maxTry = 2;
@Override
public boolean retry(ITestResult result) {
if (count < maxTry) {
count++;
System.out.println("Retrying test " + result.getName() + " for " + count + " time(s)");
return true;
}
return false;
}
}
public class SampleTest {
@Test(retryAnalyzer = RetryAnalyzer.class)
public void flakyTest() {
boolean pass = Math.random() > 0.7; // 30% chance to fail
System.out.println("Test run, pass? " + pass);
Assert.assertTrue(pass, "Random failure");
}
}