1.实现网络问题相关报错监听接口
package service.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
public class TimeoutListenerRestassured extends TestListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger(TimeoutListenerRestassured.class);
public static long restassuredTimeout; //超时时间,在接口框架CaseBase中设置并保存过来
/**
* 针对restassured接口框架网络问题的报错处理,修改报错信息
* @param tr ITestResult 对象
*/
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Override
public void onTestFailure(ITestResult tr) {
String apiName = "";
//获取当前测试执行的用例中和测试用例方法名相同的属性值
if(tr.getTestContext().getAttribute(tr.getMethod().getMethodName()) != null){
apiName = tr.getTestContext().getAttribute(tr.getMethod().getMethodName()).toString();
}
//针对不同错误类型的处理
switch (tr.getThrowable().getClass().getName()) {
case "java.net.ConnectException" -> {
tr.setThrowable(new AssertionError(tr.getMethod().getDescription() +" "+apiName+ " 网络请求失败! "+tr.getThrowable().toString()));
// 当抛出ConnectException时忽略该用例
// tr.setStatus(3);
// logger.info(tr.getThrowable().toString());
}
case "java.net.SocketTimeoutException" ->
tr.setThrowable(new AssertionError(tr.getMethod().getDescription() +" "+apiName+ " 响应超时!超时时间为"+restassuredTimeout/1000+"秒"));
case "java.net.SocketException" ->
tr.setThrowable(new AssertionError(tr.getMethod().getDescription() +" "+apiName+ " :客户端已终止(连接重置)!"));
case "java.net.UnknownHostException" ->
tr.setThrowable(new AssertionError( tr.getMethod().getDescription() +" "+apiName+ " 网络问题导致DNS解析报错!"));
}
}
}
2.在接口casebase类名称增加@Listeners注解指定实现的监听接口
3.针对数据驱动方式执行的测试用例处理
将区分的字段加到ITestContext对象当中,
//给context对象中添加和当前方法名称相同的属性,属性值为当前执行这条的具体用例名称以便在TimeoutListener*监听类中报错使用
context.setAttribute(Thread.currentThread().getStackTrace()[1].getMethodName(), param.get("name"));