TestNG实现场景恢复

发表于:2018-5-31 09:55

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:helentester    来源:博客园

  自动化测试过程中存在很多的不稳定性,例如网络的不稳定,浏览器无响应等等,这些失败往往并不是产品中的错误。那么这时我们需要对执行失败的场景恢复重新执行,确认其是否确实失败。
  以前使用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中添加如下配置:
<listeners>
<!-- 添加场景恢复的监听器 -->
<listener class-name="common.TestngRetryListener"></listener>
</listeners>
  五、结果展示
  执行完结果后,查看测试报告,测试是有失败的。
  在 log输出中,我们可以看到TClassManageTest中的方法inputClassList是重跑了三次的。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号