自动化测试系列(11)—— 测试用例(截图版)

自动化测试系列(11)—— 测试用例(截图版)

来写一个selenium+testng+reportng测试报告显示测试失败截图的测试用例


参考文章
reportng定制修改

失败后操作

    //用例结束的时候判断结果是否失败
    @AfterMethod(alwaysRun = true)
    public void afterMethod(ITestResult result) throws Exception {
        if (!result.isSuccess())
            catchExceptions(result);
    }

    //失败将设置的图片写入report
    public void catchExceptions(ITestResult result) throws IOException {
        if (!result.isSuccess()) {
            //在testng的report默认路径test-output下的html文件夹中创建一个截图文件夹以存放截图
            //截图放在这里把整个测试报告(test-output文件夹)单独打包发给别人查看也不会报错
            File file = new File("test-output/html/snapshot");
            Reporter.setCurrentTestResult(result);
            Reporter.log(file.getAbsolutePath());
            String filePath = file.getAbsolutePath();
            String dest = result.getMethod().getRealClass().getSimpleName()+"."+result.getMethod().getMethodName();
            String time = DateUtils.getCurrentDateTime2();
            String picName=filePath+File.separator+dest+time +".png";
            File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(srcFile, new File(picName));
            String escapePicName="snapshot"+File.separator+dest+time+".png";
            String openPicName=escapeString("snapshot"+File.separator+dest+time+".png");
            //window.open()实现点击图片在新窗口显示大图,其中图片路径需要转义
            String html="<img src='"+escapePicName+"' onclick='window.open(\""+openPicName+"\")'' hight='100' width='100'/>";
            Reporter.log(html);

        }
    }
    /**
     * 替换字符串
     * @param s 待替换string
     * @return 替换之后的string
     */
    public String escapeString(String s)
    {
        if (s == null)
        {
            return null;
        }

        StringBuilder buffer = new StringBuilder();
        for(int i = 0; i < s.length(); i++)
        {
            buffer.append(escapeChar(s.charAt(i)));
        }
        return buffer.toString();
    }

    /**
     * 将\字符替换为\\
     * @param character 待替换char
     * @return 替换之后的char
     */
    private String escapeChar(char character)
    {
        switch (character)
        {
            case '\\': return "\\\\";
            default: return String.valueOf(character);
        }
    }

这里我把时间工具类获取时间至毫秒的方法放一下,获取至毫秒就不用担心每分钟多次截图了

    public static String getCurrentDateTime2() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(calendar.getTime());
    }

待续


有问题请留言。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值