selenium遇到异常自动截图
最近要在框架中添加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遇到异常自动截图的更多相关文章
- Appium+Python之异常自动截图
运行过程中出现异常情况,我们怎么直观的看到呢?最简单的方法就是可以把异常现象截图下来. 思路:我这里采用get_screenshot_as_file(filename)方法,filename通过获取时 ...
- selenium 利用testNG对异常进行自动截图
哈哈哈,很久没写博客了,懒了. 因为一些原因最近需要把监听事件重新整理一下,开始没细想,直接copy网上的,其实结果发现报错很多,或者是达不到效果,然后把之前的代码翻出来,仔细看了一下.下面给一些需要 ...
- Selenium2+python自动化67-用例失败自动截图【转载】
前言: 装饰器其实就是一个以函数作为参数并返回一个替换函数的可执行函数 上一篇讲到用装饰器解决异常后自动截图,不过并没有与unittest结合,这篇把截图的装饰器改良了下,可以实现用例执行失败自动截图 ...
- testng 失败自动截图
testng执行case failed ,testng Listener会捕获执行失败,如果要实现失败自动截图,需要重写Listener的onTestFailure方法 那么首先新建一个Listene ...
- Webdriver+Testng实现测试用例失败自动截图功能
testng执行测试用例的时候,如果用例执行失败会自动截图,方便后续排查问题 1.首先定义一个截图类: package com.rrx.utils; import java.io.File;impor ...
- Selenium3+python异常后截图(screenshot)
前言 在执行用例过程中由于是无人值守的,用例运行报错的时候,我们希望能对当前屏幕截图,留下证据. 在写用例的时候,最后一步是断言,可以把截图的动作放在断言这里,那么如何在断言失败后截图呢? 一.截图方 ...
- 使用appium和testng实现Android自动截图
简单介绍 需求场景是:当测试安卓应用的脚本得到失败结果时,对当前手机屏幕截图,便于查找问题. 实现方式是:1)定义一个父类UITest,作为所有测试类的父类.在父类中UITest中定义一个截图的方法, ...
- Unittest 支持 case 失败后自动截图功能的另外两种方式
原生的unittest框架是不支持case失败后自动截图的功能的,网上看了大家的解决办法,大体上分为两种:1.要么加装饰器2.也有人封装断言这里我们看看还有没有其他的更加方便的方法值得大家一起探讨一下 ...
- selenium web driver 实现截图功能
在验证某些关键步骤时,需要截个图来记录一下当时的情况 Webdriver截图时,需要引入 import java.io.File; import java.io.IOException; import ...
随机推荐
- ActiveReports 报表应用教程 (4)---分栏报表
在 ActiveReports 中可以实现分栏报表布局样式,可以设置横向分栏.纵向分栏,同时进行分栏和分组设置,统计分栏分组的小计.合计等.在商业报表系统中常见的分栏报表有商品标签.员工工卡.条码打印 ...
- LeetCode129:Sum Root to Leaf Numbers
题目: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a nu ...
- hadoop pipes wordcount compile
http://devel.cs.stolaf.edu/projects/bw/wiki.real/index.php/Hadoop_Reference,_January_2011 http://guo ...
- jquery自定义插件——window的实现
本例子实现弹窗的效果: 1.jquery.show.js /* * 开发者:lzugis * 开发时间:2014年6月10日 * 实现功能:点击在鼠标位置显示div * 版本序号:1.0 */ (fu ...
- 多准则决策模型-TOPSIS评价方法-源码
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 ...
- 1、Flat UI Getting started(文档翻译)
下载链接:http://www.bootcss.com/p/flat-ui/ 一.什么是Flat UI? Flat UI 是一种漂亮的Boostrap主题.我们重新设计了它的很多组件,使得其看起来扁平 ...
- SAP 金额在表中的存储及货币转换因子
场景:一个接口出问题了,SAP通过RFC将SO数据传输到Java系统,错误的将100日元传为1.00日元. 其实查看SAP透明表发现,表中存储的的确是1.00,是前台真实数据的1/100,开发接口时没 ...
- android 打包错误
打包时报如下错误: Export aborted because fatal lint errors were found. These are listed in the Lint View. Ei ...
- Python基础(10)--数字
本文的主题是 Python 中的数字.会详细介绍每一种数字类型,它们适用的各种运算符, 以及用于处理数字的内建函数.在文章的末尾, 简单介绍了几个标准库中用于处理数字的模块. 本文地址:http:// ...
- (原创)android Sqlite多线程访问异常解决方案
在开发Android的程序的时候sqlite数据库是经常用到的:在多线程访问数据库的时候会出现这样的异常:java.lang.IllegalStateException: Cannot perform ...