最近要在框架中添加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. redis3.0 集群实战1 -- 安装和配置

    本文主要是在centos7上安装和配置redis集群实战 参考: http://hot66hot.iteye.com/blog/2050676 集群教程: http://redisdoc.com/to ...

  2. java获取class所在jar

    在类库的开发过程中,有些时候为了self-contain的原因,我们希望所有的资源都打包在jar中,但是有些工具好像无法支持从classpasth直接获取比如velocity的模板合并,此时我们就知道 ...

  3. (HY000): Cannot modify @@session.sql_log_bin inside a transaction

    昨天,线上发生一例(HY000): Cannot modify @@session.sql_log_bin inside a transaction代码缺少显示的start transaction控制 ...

  4. jQuery Flickerplate 幻灯片

    Flickerplate 是个轻量级 jQuery 插件,大小仅为 12 kb.它允许用户点击鼠标然后转换内容,非常容易使用,响应式,支持触摸设备 在线实例 默认 圆点导航位置 动画方式 深色主题 H ...

  5. WCF服务部署到IIS7.5

    下面介绍如何把WCF服务部署到IIS: 为WCF服务创建.svc文件 我们知道,每一个ASP.NET Web服务都具有一个.asmx文本文件,客户端通过访问.asmx文件实现对相应Web服务的调用.与 ...

  6. SAP ALV中同一列的不同行显示不同的小数位,并能够总计,小计

    物料数量字段,根据物料类型的不同,来显示不同的小数位:要求有点苛刻: 首先,要能够总计和小计的话,这一列的字段类型必须是数值类型. 这样的话,就不能通过截取的方式改变不同行的小数位. 以下是两种思路: ...

  7. MapGIS转Shp文件的单位问题

    在MapGIS浏览查看一下数据,各种不习惯:用mapgis自带的转shp功能,属性表会出错:利用名为map2shp的试用版软件可将mapgis格式的数据较为良好转成shp格式.但经常会遇到一个单位问题 ...

  8. Fix Internet Explorer Crashes with SharePoint 2013 Online Presence Indicators

    IE中,只要是鼠标浮动到人名字上面的状态的时候,这个状态是与Lync相连接的,IE就会出现停止工作. 以下是解决方法. Until the other day when I figured this ...

  9. AndroidDevTools下载地址

    Android Dev Tools官网地址:www.androiddevtools.cn http://www.androiddevtools.cn/ http://wear.techbrood.co ...

  10. Mac平台下启动MySQL到完全终止MySQL----终端八步走

    1.选中Finder的情况下,快捷键进入搜索目录:/usr/local 然后进入mysql目录下: 2.右键 "从这里启动" 打开终端: 3.输入执行:./scripts/mysq ...