[唐胡璐]Selenium技巧- 抓图并保存到TestNG报告中
这里不讲解怎么在Eclipse安装配置TestNG,网上一搜一大把,大家自己去实践一下。
在这里主要说一下用Java来实现Selenium Webdriver的截图功能和把截图写到TestNG的报告中。
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
|
//Capture screenshot public String captureScreenShot()
{ String dir = "screenshot" ;
String date = new SimpleDateFormat( "yyyyMMdd" ).format( new Date());
String time = new SimpleDateFormat( "HHmmss" ).format( new Date());
String screenShotPath = dir + File.separator + date + File.separator + time + ".png" ;
try
{
File source = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File(screenShotPath));
screenShotPath = screenShotPath.substring(screenShotPath.indexOf( "\\" ));
}
catch (IOException e)
{
screenShotPath = "Failed to capture screenshot: " + e.getMessage();
}
return screenShotPath;
} //Write to TestNG public void writeToTestNG(String proMessage) {
String png = captureScreenShot();
Reporter.log( "[" + logTime + "] " + proMessage);
String log = new File( "screenshot" ).getAbsolutePath();
Reporter.log( "<br/><img src=\"" + log + "/" + png + "\" />" );
} |
用下面的方法来调用:
1
2
3
4
5
6
7
8
9
10
11
|
@Test public void search()
{ openURL();
BaiduSearch yy = new BaiduSearch(driver);
yy.searchFor( "searchTest" );
writeToTestNG( "testing " );
driver.quit();
} |
运行结果如下图所示: