testng实现场景恢复

自动化测试过程中存在很多的不稳定性,例如网络的不稳定,浏览器无响应等等,这些失败往往并不是产品中的错误。那么这时我们需要对执行失败的场景恢复重新执行,确认其是否确实失败。

以前使用QTP的时候也使用了场景恢复,那么testng的场景恢复怎么做呢?

一、查看testng现在接口

首先,我们来看一下TestNG的IRetryAnalyzer接口(因为我的项目是用maven管理,所以接口位置是:Maven Dependencies-testng.jar-org.testng-IRetryAnalyzer.class)

package org.testng;

/**
* Interface to implement to be able to have a chance to retry a failed test.
*
* @author tocman@gmail.com (Jeremie Lenfant-Engelmann)
*
*/
public interface IRetryAnalyzer { /**
* Returns true if the test method has to be retried, false otherwise.
*
* @param result The result of the test method that just ran.
* @return true if the test method has to be retried, false otherwise.
*/
public boolean retry(ITestResult result);
}
这个接口只有一个方法:
  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>

五、结果展示

  执行完结果后,查看测试报告,测试是有失败的。

  testng实现场景恢复

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

  testng实现场景恢复

上一篇:bootstrap-datetimepicker.js学习


下一篇:PHP环境配置综合篇