这是我参与8月更文挑战的第26天,活动详情查看:8月更文挑战
我们在实际的工作中会遇到有时候不是因为接口错误导致的用例之行失败,那么我门就需要在用例之行失败后,我们进行重试,减少因为环境或者特殊情况导致的用例执行失败,减少过程中,误报的情况。我们之前看的都是python的,今天我们来看下java,我们来看看怎么来重写testNG里面的用例重试。
我们可以去看下testNG之行的代码,那么我们可以找到,我们需要重写的线索,
来重新IRetryAnalyzer类就可以实现我们的用例的重试的执行,我们可以看下,我们是如何实现的。
public class TestNGRetry implements IRetryAnalyzer {
private int retryCount = 1;
private static final int maxRetryCount = 3;
@Override
public boolean retry(ITestResult result) {
if (retryCount<=maxRetryCount){
retryCount++;
return true;
}
return false;
}
public void reSetCount(){
retryCount=1;
}
}
使用的时候,在测试方法上面
@Test(retryAnalyzer= TestNGRetry.class)
可以写个监听器,放到xml配置里面,这样所有的测试用例都能用这个重试方法了,方便后续的应用。
public class RetryListener implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor,
Method testMethod) {
IRetryAnalyzer retryAnalyzer = annotation.getRetryAnalyzer();//获取到retryAnalyzer的注解
if (retryAnalyzer == null){ annotation.setRetryAnalyzer(TestNGRetry.class);
}
}
}
那么我们需要怎么去写我们的配置文件呢,下面展示的就是对应的配置文件
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false" thread-count="2">
<listeners>
<listener
class-name="chongshi.tesng.TestRunnerListener" />
<listener class-name="chongshi.tesng.RetryListener"/>
</listeners>
<test name="Test">
<classes>
<class name="chongshi.tesng.New"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
这样我们就可以在配置文件中执行了。