selenium之如何截图,留下程序不听话的证据!

一.概述

      知道吗,selenium在执行测试用例的时候,肯定会有执行失败的用例,那么在用例执行失败的那一刻,你能

怎么办呢,就像跟警察破案一样,要得到当时的监控画面,selenium也可以直接截图留下用例执行失败的有效依据,

那么如何截图呢,请看下文分解,你一定会有小小的收获。

二.编写一个截图类ScreenShot

 1 package com.daanhealth.tnb.util;
 2 
 3 import java.io.File;
 4 
 5 import org.apache.commons.io.FileUtils;
 6 import org.openqa.selenium.OutputType;
 7 import org.openqa.selenium.TakesScreenshot;
 8 import org.openqa.selenium.WebDriver;
 9 
10 public class ScreenShot {
11     
12     public WebDriver driver;
13     
14     public ScreenShot(WebDriver driver){
15         this.driver=driver;
16     }
17     
18     private void takeScreenshot(String screenPath){
19         try {
20             File srcFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
21             FileUtils.copyFile(srcFile, new File(screenPath));
22         } catch (Exception e) {
23             // TODO: handle exception
24             System.out.println("Screen shot error: " + screenPath);
25         }
26     }
27     
28     public void takeScreenshot(){
29         String screenName=new DateFormat().formatDateToString(System.currentTimeMillis())+".jpg";
30         File dir=new File("test-output/snapshot");
31         if(!dir.exists()){
32             dir.mkdirs();
33         }
34         String screenPath=dir.getAbsolutePath()+File.separator+screenName;
35         takeScreenshot(screenPath);
36     }
37 
38 }
View Code

 

posted @ 2015-12-01 16:04  li_wu  阅读(1590)  评论(0编辑  收藏  举报