Web自动化测试Java篇01-Web自动化测试re-run机制

使用Java+TestNG框架运行测试用例时,会遇到因网速等不稳定因素导致用例执行失败情况,需再次手动验证查看,降低自动化测试效率,采用如下re-run机制可有效提高UI自动化测试效率。

优点:使用简单,可复用性强,系统耦合性低。

已解决问题:多次失败reRun后测试报告中不会重复计算多条用例数。

实现步骤如下:

1、编写Rerun.java(此脚本可直接复用)

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class Rerun implements IRetryAnalyzer {
private int retryCount = 0;
private int maxRetryCount = 1;
@Override
public boolean retry(ITestResult result) {
if (retryCount retryCount++;
return true;
}
return false;
}
}

2、编写RerunListener.java(此脚本可直接复用)
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;

public class RerunListener implements IAnnotationTransformer {

public void transform(ITestAnnotation annotation, Class testClass,
                      Constructor testConstructor, Method testMethod) {
    IRetryAnalyzer retry = annotation.getRetryAnalyzer();
    if (retry == null) {
        annotation.setRetryAnalyzer(Rerun.class);
    }
}

}

3、编写TestCountListener.java(此脚本可直接复用)

import java.util.Iterator;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;

public class TestCountListener implements ITestListener {

@Override
public void onFinish(ITestContext context) {
    Iterator listOfFailedTests = context.getFailedTests().getAllResults().iterator();
    while (listOfFailedTests.hasNext()) {
        ITestResult failedTest = listOfFailedTests.next();
        ITestNGMethod method = failedTest.getMethod();
        if (context.getFailedTests().getResults(method).size() > 0) {
            listOfFailedTests.remove();
        } else if (context.getPassedTests().getResults(method).size() > 0) {
            listOfFailedTests.remove();
        }else if (context.getSkippedTests().getResults(method).size() > 0) {
            listOfFailedTests.remove();
        }
    }
}


public void onTestStart(ITestResult result) {
    // TODO Auto-generated method stub
}

public void onTestSuccess(ITestResult result) {
    // TODO Auto-generated method stub
}

public void onTestFailure(ITestResult result) {
    // TODO  Auto-generated method stub
}

public void onTestSkipped(ITestResult result) {
    // TODO Auto-generated method stub
}

public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
    // TODO Auto-generated method stub
}

public void onStart(ITestContext context) {
    // TODO Auto-generated method stub
}

}

你可能感兴趣的:(自动化测试,web自动化测试,软件测试)