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 ...
随机推荐
- csharp: 百度语音合成
public string API_id = "3333"; //你的ID public string API_record = null; public string API_r ...
- AC自动机---Searching the String
ZOJ 3228 题目网址:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=16401 Description Little ...
- winform(容器、打印、对话框)
一.布局:2个属性:Anchor:锁定位置Dock:填充位置一般Dock是与容器控件配合使用 二.容器控件:Panel:就是一个区域,类似于DIV,可以独立布局,还可以让其它控件及容器在它的内部再次布 ...
- 如果一个游戏上面加一个透明层,js能不能实现 点击透明层的任意点 而正常玩游戏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 使用checkbox实现纯CSS下拉框
在这个例子中,我们会看到一个纯CSS制作的下拉框.主要是要用到了HTML元素的checkbox 和CSS3选择器,并没有用到JavaScript.例子如下: Click to Expand Link ...
- WampServer搭建php环境可能遇到的问题
WampServer搭建php环境可能遇到的问题 1.安装时报错,缺少 MSVCR100.dll 文件 这是因为wampServer安装时用到的vc库没有更新,要安装更新之后再进行安装,因为之前安装的 ...
- nutch简介
1.什么是 nutch Nutch 是一个开源的. Java 实现的搜索引擎.它提供了我们运行自己的搜 索引擎所需的全部工具.2.研究 nutch 的原因(1) 透明度: nutch 是开放源代码的, ...
- C安全编码--预处理
建议和规则 建议: 用内联函数或静态函数代替与函数相似的宏 在宏参数名两边加上括号 宏替换列表应该加上括号 应该使用typedef定义编码类型 不要复用标准头文件名 理解连接标记或执行字符串化时的宏替 ...
- 【读书笔记】iOS-Xcode知识-多线程
一,Xcode使用的调试器是GDB.GDB是GNU项目的一部分,它可以在很多不同的平台上使用.如果你愿意,可以通过命令行来运行它.GDB有着完善的文档系统,尽管它的文档有些难于理解并且网络上流传着好几 ...
- iOS开发之网络编程--2、NSURLSessionDownloadTask文件下载
本文内容大纲: 1.回顾NSURLSessionTask 2.NSURLSessionDownloadTask大文件之block下载 3.NSURLSessionDownloadTask大文件之代理方 ...