白羽
2018-05-31
来源 :网络
阅读 2312
评论 0
摘要: 自动化测试过程中存在很多的不稳定性,例如网络的不稳定,浏览器无响应等等,这些失败往往并不是产品中的错误。那么这时我们需要对执行失败的场景恢复重新执行,确认其是否确实失败。
自动化测试过程中存在很多的不稳定性,例如网络的不稳定,浏览器无响应等等,这些失败往往并不是产品中的错误。那么这时我们需要对执行失败的场景恢复重新执行,确认其是否确实失败。
以前使用QTP的时候也使用了场景恢复,那么testng的场景恢复怎么做呢?
一、查看testng现在接口
首先,我们来看一下TestNG的IRetryAnalyzer接口(因为我的项目是用maven管理,所以接口位置是:Maven Dependencies-testng.jar-org.testng
-IRetryAnalyzer.class)
packageorg.testng;
/**
*Interfacetoimplementtobeabletohaveachancetoretryafailedtest.
*
*@authortocman@gmail.com(JeremieLenfant-Engelmann)
*
*/
publicinterfaceIRetryAnalyzer{
/**
*Returnstrueifthetestmethodhastoberetried,falseotherwise.
*
*@paramresultTheresultofthetestmethodthatjustran.
*@returntrueifthetestmethodhastoberetried,falseotherwise.
*/
publicbooleanretry(ITestResultresult);
}
这个接口只有一个方法:
public boolean retry(ITestResult result);
一旦测试方法失败,就会调用此方法。如果您想重新执行失败的测试用例,那么就让此方法返回true,如果不想重新执行测试用例,则返回false。
二、实现testng失败重跑的接口IRetryAnalyzer
添加类TestngRetry,实现如下:
/**
* @author Helen
* @date 2018年5月19日
*/
package common;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
import org.testng.Reporter;
/**
* 描述:重写testngRetry接口,设置场景恢复
*/
public class TestngRetry implements IRetryAnalyzer {
private int retryCount = 1;
private static int maxRetryCount = 3;// 最大重新执行场景的次数
/** 场景恢复设置,重新执行失败用例的次数
*/
public boolean retry(ITestResult result) {
if (retryCount <= maxRetryCount) {
String message = "Retry for [" + result.getName() + "] on class [" + result.getTestClass().getName()
+ "] Retry " + retryCount + " times";
Reporter.setCurrentTestResult(result);
Reporter.log(message);//报告中输出日志
retryCount++;
return true;
}
return false;
}
}
三、添加监听
这时我们还要通过接用IAnnotationTransformer来实现监听,添加类TestngRetryListener,代码如下:
/**
* @author Helen
* @date 2018年5月19日
*/
package common;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
/**
* 描述:实现IAnnotationTransformer接口,设置监听
*/
public class TestngRetryListener implements IAnnotationTransformer{
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = annotation.getRetryAnalyzer();
if (retry == null) {
annotation.setRetryAnalyzer(TestngRetry.class);
}
}
}
四、配置testng监听器
最后,我们只要在testng.xml里面设置监听就可以了,在testng.xml中添加如下配置:
五、结果展示
执行完结果后,查看测试报告,测试是有失败的。

在 log输出中,我们可以看到TClassManageTest中的方法inputClassList是重跑了三次的。

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标软件测试之测试工具频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号