zoukankan      html  css  js  c++  java
  • Webdriver+Testng实现测试用例失败自动截图功能

           testng执行测试用例的时候,如果用例执行失败会自动截图,方便后续排查问题

    1.首先定义一个截图类:

    package com.rrx.utils;

    import java.io.File;
    import java.io.IOException;
    import java.util.Date;

    import org.apache.commons.io.FileUtils;
    import org.openqa.selenium.OutputType;
    import org.openqa.selenium.TakesScreenshot;
    import org.openqa.selenium.WebDriver;


    public class ScreenShort {
    public WebDriver driver;

    public ScreenShort(WebDriver driver) {
    this.driver = driver;
    }

    public void takeScreenshot(String screenPath){
    try {
    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(screenPath));
    } catch (IOException e) {
    System.out.println("Screen shot error: " + screenPath);
    }

    }

    public void takeScreenshot(){
    String screenName=String.valueOf(new Date().getTime()+".jpg");
    File file=new File("C://Users//Administrator//workspace//Selenium"+File.separator+"test-output");
    //System.out.println(File.separator);//就是一个/
    if (!file.exists())
    file.mkdirs();

    String screenPath = file.getAbsolutePath() + "\" + screenName;
    this.takeScreenshot(screenPath);
    }
    }

    2.实现testng的listener接口并重写OnTestFailure方法

    package com.rrx.utils;

    import org.testng.ITestResult;
    import org.testng.TestListenerAdapter;

    public class Listener extends TestListenerAdapter {
    @Override
    public void onTestFailure(ITestResult tr){

    try {
    ScreenShort sc=new ScreenShort(DriverFactory.getDriver());
    sc.takeScreenshot();

    } catch (SecurityException e) {
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    }
    }
    }

    3.加上监听

    @Listeners({ DotTestListener.class })

    或者直接在testNG配置文件中添加

    <listeners>
    <listener class-name="com.rrx.utils.Listener" />
    </listeners>

  • 相关阅读:
    [技巧] 使用Word2010直接编辑、发布博客→博客园cnblogs
    POJ 1201 Intervals【差分约束】
    HDU 2896 病毒侵袭【AC自动机】
    opengl中的gluOrtho2D【转】
    【转】x86和x64的含义和区别
    POJ 1704 Georgia and Bob【Nim博弈】
    POJ 1947 Rebuilding Roads【树状DP】
    POJ 3207/ POJ 3678 【2SAT】
    POJ 1067 取石子游戏【威佐夫博奕】
    apache+webdav的安装配置
  • 原文地址:https://www.cnblogs.com/liwei09k1/p/7987667.html
Copyright © 2011-2022 走看看