java+testng框架接口自动化测试网络超时、连接重置等报错自定义。以及以数据驱动方式执行时怎么区分报错内容。

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"));

在这里插入图片描述

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值