Selenium抓图并保存到TestNG报告中

这里不讲解怎么在Eclipse安装配置TestNG,网上一搜一大把,大家自己去实践一下。
在这里主要说一下用Java来实现Selenium Webdriver的截图功能和把截图写到TestNG的报告中。

Capture screenshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//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

1
2
3
4
5
6
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 + "\" />");

Call function

1
2
3
4
5
6
7
8
9
@Test
public void search()
{

openURL();
BaiduSearch yy = new BaiduSearch(driver);
yy.searchFor("searchTest");
writeToTestNG("testing ");
driver.quit();
}

Result

TestNG

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!