其他测试框架 自动化测试用例失败重跑方案

Alan · 2017年03月09日 · 最后由 cctodd 回复于 2018年01月18日 · 1659 次阅读

在自动化测试执行过程中,难免会出现因为执行机的环境或者延时等问题导致的用例失败问题,对于这些非功能问题导致的用例执行失败,我们希望这个用例能够重新执行一次或几次,从而尽量让最终的测试结果是功能相关的 fail……面对这个自动化测试的需求点,我曾经在 TestNG 中实现过,今天有人问起,就将之前的实现思路写下来分享给大家。

一、实现思路:
在 TestNG 的@AfterMethod 注解方法中,添加测试执行结果的监听,通过 TestNG 提供的 ITestResult 接口去判断测试执行是否成功,如果失败了就通过反射获取到当前执行失败用例的类名和方法名,然后调用方法,实现了重跑一次(或多次,次数可以自己设定)。实现逻辑图如下:

二、代码逻辑:
@AfterMethod注解中的代码如下:

@AfterMethod
    public void afterMethod(ITestResult result) {
        System.out.println("BaseCase: afterMethod");
        String testClassName = String.format("%s.%s", result.getMethod()
                .getRealClass().getName().toString(), result.getMethod().getMethodName());
        System.out.println("---->"+testClassName);
        if (!result.isSuccess()) {
            Log.fail(result.getThrowable());
        }
        Log.info("==============测试执行完毕==============");
        if(Log.isPass()){
            TestReport.successCount ++;
        }else{
            if(LogConfig.retryTimes > 0){

                try {
                    Class<?> c = Class.forName(result.getMethod().getRealClass().getName());
                    Method m =   c.getMethod(result.getMethod().getMethodName());
                    while(retryCounter < LogConfig.retryTimes){
                        Log.flush();
                        Log.info("<<<<<<<<<<<<<<<<<< 开始重新执行\""+ result.getMethod().getMethodName() +"\"方法 >>>>>>>>>>>>>>>>>>");
                        m.invoke(c.newInstance(), (Object[])null);
                        Log.info("<<<<<<<<<<<<<<<<<< 重新执行\""+ result.getMethod().getMethodName() +"\"方法完毕 >>>>>>>>>>>>>>>>>>");
                        retryCounter ++;
                    }
                } catch (Exception e) {                        
                    e.printStackTrace();
                }
                if(retryCounter >= LogConfig.retryTimes) {
                    retryCounter = 0;//初始化
                    TestReport.failureCount ++;
                }
            }else{
                TestReport.failureCount ++;
            }
        }

        Log.commit();
    }

上面代码中用到的 Log 类,就是使用之前写过的日志和报告框架 Log4Reports,传送门:http://www.jianshu.com/p/2c3fd46e2357

三、执行效果:
test2() 方法执行失败后,重跑了一次的效果:

原文链接:http://www.jianshu.com/p/00e7cdeab9f4

共收到 2 条回复 时间 点赞

这样最后统计的用例数会因为重跑不准确

楼主开源的精神很棒。
m.invoke(c.newInstance(), (Object[])null);

不能使用 dataProvider 的话,意义不大呀,和 testNG 添加 listener 来实现重跑的方法类似,解决不了这个问题。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册