写了三个失败用例重跑的 class

public class RetryListener implements IAnnotationTransformer {

    @Override
    public void transform(ITestAnnotation annotation, @SuppressWarnings("rawtypes") Class testClass, @SuppressWarnings("rawtypes") Constructor testConstructor, Method testMethod) {
        // TODO Auto-generated method stub
          //1.初始化IRetryAnalyzer对象
        IRetryAnalyzer iRetryAnalyzer = annotation.getRetryAnalyzer();
        //判断测试方法是否设置重跑属性
        if (iRetryAnalyzer == null) {
            //为空说明用例方法里面未设置重跑,则按照全局设置进行用例重跑
            //如果用例方法设置了注解属性retryAnalyzer,则按照注解的重跑
            annotation.setRetryAnalyzer(TestCaseRetry.class);
        }
    }

public class TestCaseRetry implements IRetryAnalyzer{
     private static Logger logger = Logger.getLogger(TestCaseRetry.class);
        //当前正在进行的重试次数
     public static int currentCount = 1;
        //允许重试的最大次数
     private int maxCount = 2;


    @Override
    public boolean retry(ITestResult result) {
          logger.info("当前重试次数是【" + currentCount + "】");
            if (currentCount < maxCount) {
                logger.info("当前测试方法【" + result.getName() + "】执行失败,进入失败用例重试模式,正在进行第【" + currentCount + "】次重试");
                currentCount++;
                return true;
            }
            return false;
    }
public class CustomListener extends TestListenerAdapter{
    private static Logger logger = Logger.getLogger(CustomListener.class);
    @Override
    public void onTestFailure(ITestResult tr) {
        super.onTestFailure(tr);//如果测试用例执行完所有重试以后依然失败的话,重新设置currentCount为初始值,方便其他用例执行重试
        logger.info("用例执行失败,重试机制的次数恢复初始值");
        TestCaseRetry.currentCount = 1;
        super.onTestFailure(tr);

    }

    @Override
    public void onTestSuccess(ITestResult tr) {
        //如果测试用例执行重试的时候,执行成功了,也需要设置currentCount为初始值,方便其他用例执行重试
        logger.info("用例执行成功,重试机制的次数恢复初始值");
        TestCaseRetry.currentCount = 1;
        super.onTestSuccess(tr);
    }
    @Override
    public void onFinish(ITestContext testContext) {
        super.onFinish(testContext);
        Iterator<ITestResult> listOfFailedTests = testContext.getFailedTests().getAllResults().iterator();
        while (listOfFailedTests.hasNext()) {
            ITestResult failedTest = (ITestResult) listOfFailedTests.next();
            ITestNGMethod method = failedTest.getMethod();
            if (testContext.getFailedTests().getResults(method).size() > 1) {
                listOfFailedTests.remove();
            } else {
                if (testContext.getPassedTests().getResults(method).size() > 0) {
                    listOfFailedTests.remove();
                }
            }}}
}

然后在 testng.xml 上添加了这两个监听类

在 testng 用例上直接执行,写的失败重跑生效。然后用 ant 去执行就一直在失败重跑


↙↙↙阅读原文可查看相关链接,并与作者交流