最近要在框架中添加case失败时,要自动截图,主要又两种方式,思想都是在抛异常的时候,捕获到异常,并作页面截图处理。今天坐下总结。

一、第一种方式,重写onException方法

只针对webdriver的异常截图,该方法由于只针对webdriver抛的异常时才能截图,有一定的限制

a.继承AbstractWebDriverEventListener类,重写onException方法,

    public void onException(java.lang.Throwable throwable,
WebDriver driver){ Throwable cause = throwable.getCause();
    /*
    String cause = throwable.getClass().getName();
    ScreenshotException ec = new ScreenshotException(cause);
    */
System.out.println(throwable.getClass().getName());
System.out.println("onException=" + cause); Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String dateString = formatter.format(currentTime);
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try { File screenshot = new File("D:/ddd/"
+ dateString + ".png");
FileUtils.copyFile(scrFile,screenshot);
} catch (IOException e) {
e.printStackTrace();
}
}

b.测试类,要用EventFiringWebDriver ,并注册MyListen

    public static void main(String args[]) {

        String key = "webdriver.chrome.driver";
String value = "D:/BaiduYunDownload/selenium/chromedriver.exe";
System.setProperty(key, value);
WebDriver dr = new ChromeDriver(); EventFiringWebDriver event = new EventFiringWebDriver(dr);
MyListen ml = new MyListen();
event.register(ml);
dr = event;
dr.get("http://www.baidu.com");
dr.findElement(By.id("kw1")).sendKeys("test");
//System.out.println(5/0); Assert.assertEquals("haha", event.findElement(By.id("su")).getAttribute("value"));
event.quit(); }

二、第二种方式:使用testNG的TestListenerAdapter

a.先建一个类继承TestListenerAdapter,并重写onTestFailure方法

package com.screenshot.exception;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date; import org.apache.commons.io.FileUtils;
import org.apache.velocity.runtime.log.LogManager;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter; import com.screenshot.singleton.TestBase; /**
* @author QiaoJiaofei
* @version 创建时间:2015年8月24日 下午6:33:44
* 类说明
*/
public class UseTestNg extends TestListenerAdapter{ @Override
public synchronized void onTestFailure(ITestResult result) {
Object currentClass = result.getInstance();
WebDriver webDriver = ((TestUsNg) currentClass).getDriver(); if (webDriver != null)
{
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String dateString = formatter.format(currentTime);
File scrFile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
try { File screenshot = new File("D:/ddd/"
+ dateString + ".png");
FileUtils.copyFile(scrFile,screenshot);
} catch (IOException e) {
e.printStackTrace();
} }
}
}

b.创建测试类,注意需要在测试类中写getDriver()方法

package com.screenshot.exception;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test; /**
* @author QiaoJiaofei
* @version 创建时间:2015年8月24日 下午6:43:44
* 类说明
*/
public class TestUsNg {
private WebDriver dr;
public WebDriver getDriver() {
return dr;
} @Test
public void f() {
String key = "webdriver.chrome.driver";
String value = "D:/BaiduYunDownload/selenium/chromedriver.exe";
System.setProperty(key, value);
dr = new ChromeDriver();
System.out.println(5/0);
}
}

C.在testng的xml文件中添加监听

<listeners>

<listener class-name="com.screenshot.exception.UseTestNg" />

</listeners>

D.测试类继承该类,每个子类前面要加:@Listeners({com.gm.base.MyListener.class})

三、如何将生成的图片连接到reportNG中,将下面的代码放入上面相应重写的方法中,图片路径与上述代码中生成的图片结合一起。

String imgName = "";//图片路径
Reporter.log("<a href=./img/" + imgName + " target=_blank>Failed Screen Shot</a>", true);

题外:使用Robot主动截图,这种可以在自己想截图的时候调用该方法即可截当前界面

package com.screenshot.book;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File; import javax.imageio.ImageIO; import org.testng.annotations.Test; /**
* @author QiaoJiaofei
* @version 创建时间:2015年8月26日 下午7:40:34
* 类说明
*/
public class TestRobot {
@Test
public void takeScreenShotMethod(){
try{
Thread.sleep(3000);
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("D:/ddd/screenshot.jpg"));
}
catch(Exception e){
e.printStackTrace();
}
}
}

备注:

使用junit自动截图,可以使用Rule,由于我用的是testNG,所以没有调试junit的方法。详细参考:http://stackoverflow.com/questions/20995722/when-does-onexception-get-triggered-in-webdrivereventlistener

@Rule
public TestRule testWatcher = new TestWatcher() { @Override
public void succeeded(Description test){
for (LogEntry log : driver.manage().logs().get(LogType.DRIVER).getAll()) {
System.out.println("Level:" + log.getLevel().getName());
System.out.println("Message:" + log.getMessage());
System.out.println("Time:" + log.getTimestamp());
System.out.println("-----------------------------------------------");
}
System.out.println(); @Override
public void failed(Throwable t, Description test) { String testName = test.getClassName();
String subTestName = test.getMethodName();
String screenShotName = String.format("%s\\%s", testName, screenShotName);
if (driver instanceof TakesScreenshot) {
File tempFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
System.out.println(">>>>>>>>>>LOGS: " + yourDirForImages + "\\" + screenShotName + ".png");
FileUtils.copyFile(tempFile, new File(String.format("%s.png", screenShotName)));
} catch (IOException e) {
e.printStackTrace();
}
}

selenium遇到异常自动截图的更多相关文章

  1. Appium+Python之异常自动截图

    运行过程中出现异常情况,我们怎么直观的看到呢?最简单的方法就是可以把异常现象截图下来. 思路:我这里采用get_screenshot_as_file(filename)方法,filename通过获取时 ...

  2. selenium 利用testNG对异常进行自动截图

    哈哈哈,很久没写博客了,懒了. 因为一些原因最近需要把监听事件重新整理一下,开始没细想,直接copy网上的,其实结果发现报错很多,或者是达不到效果,然后把之前的代码翻出来,仔细看了一下.下面给一些需要 ...

  3. Selenium2+python自动化67-用例失败自动截图【转载】

    前言: 装饰器其实就是一个以函数作为参数并返回一个替换函数的可执行函数 上一篇讲到用装饰器解决异常后自动截图,不过并没有与unittest结合,这篇把截图的装饰器改良了下,可以实现用例执行失败自动截图 ...

  4. testng 失败自动截图

    testng执行case failed ,testng Listener会捕获执行失败,如果要实现失败自动截图,需要重写Listener的onTestFailure方法 那么首先新建一个Listene ...

  5. Webdriver+Testng实现测试用例失败自动截图功能

    testng执行测试用例的时候,如果用例执行失败会自动截图,方便后续排查问题 1.首先定义一个截图类: package com.rrx.utils; import java.io.File;impor ...

  6. Selenium3+python异常后截图(screenshot)

    前言 在执行用例过程中由于是无人值守的,用例运行报错的时候,我们希望能对当前屏幕截图,留下证据. 在写用例的时候,最后一步是断言,可以把截图的动作放在断言这里,那么如何在断言失败后截图呢? 一.截图方 ...

  7. 使用appium和testng实现Android自动截图

    简单介绍 需求场景是:当测试安卓应用的脚本得到失败结果时,对当前手机屏幕截图,便于查找问题. 实现方式是:1)定义一个父类UITest,作为所有测试类的父类.在父类中UITest中定义一个截图的方法, ...

  8. Unittest 支持 case 失败后自动截图功能的另外两种方式

    原生的unittest框架是不支持case失败后自动截图的功能的,网上看了大家的解决办法,大体上分为两种:1.要么加装饰器2.也有人封装断言这里我们看看还有没有其他的更加方便的方法值得大家一起探讨一下 ...

  9. selenium web driver 实现截图功能

    在验证某些关键步骤时,需要截个图来记录一下当时的情况 Webdriver截图时,需要引入 import java.io.File; import java.io.IOException; import ...

随机推荐

  1. EntityFramework left join

       var result = from u in db.Order                              join n in db.Equipment on u.OrderId  ...

  2. 创建WCF服务自我寄宿

    WCF服务的寄宿方式 WCF寄宿方式是一种非常灵活的操作,可以寄宿在各种进程之中,常见的寄宿有: IIS服务.Windows服务.Winform程序.控制台程序中进行寄宿,从而实现WCF服务的运行,为 ...

  3. android 学习资料

    Fragment 事件分发机制 事件分发机制2 NDK JNI ndk { moduleName "mymodule" ldLibs "log" stl &qu ...

  4. FL2440驱动添加(5)ADC驱动学习笔记

    由图可知,模拟ADC分为两部分功能,一部分是触屏功能,另一部分就是普通ADC功能.分别可以产生INT_TC和INT_ADC 两个中断.该ADC模块总共有8个通道可以进行模拟信号的输入,分别是AIN0. ...

  5. C语言回滚(二)--循环打印

    //1.用循环打印 /* FFEFEDFEDCFEDCBFEDCBA */ #include <stdio.h> #include<stdlib.h> int main(){ ...

  6. Verilog学习笔记设计和验证篇(三)...............同步有限状态机的指导原则

    因为大多数的FPGA内部的触发器数目相当多,又加上独热码状态机(one hot code machine)的译码逻辑最为简单,所以在FPGA实现状态机时,往往采用独热码状态机(即每个状态只有一个寄存器 ...

  7. ahjesus 部署lighttpd

    这个就不写了,直接传送门过去看,按照说的做就可以了 如果你想要安装最新版的,传送门 需要注意的是configure这一步,你看完他的help以后还要输入 ./configure 才能继续下一步 再就是 ...

  8. SwipeRefreshLayout下拉刷新

    1.SwipeRefreshLayout是Google在support v4 19.1版本的library更新的一个下拉刷新组件,实现刷新效果更方便. 弊端:只有下拉 //设置刷新控件圈圈的颜色 sw ...

  9. 误报的java.sql.SQLException: Parameter number 21 is not an OUT parameter

    今天为了模拟一个mysql内存不释放问题,要测试一个存储过程,同时具有出参和入参,启动时报了上述错误. <select id="funcl_trd_secu_execution_que ...

  10. SQL数据库基础(二)

    数据类型: --类似于C#中的数据类型 Datetime   范围是:1753.1.1—— 9999.12.31 Smalldatetime      1900.1.1 ——2079.6.6 操作: ...