Saturday, 26 August 2017

Code to take Screen Shots in Selenium WebDriver?


In this post, I will tell you that how would you capture the failure screenshots in Selenium WebDriver. A screenshot is the best way in order to tell the reason of automation script failure. By which a tester get the reason that on which page script gets failed and what was the reason. I am sharing the code of this with you.

Code:-


public class TakeScreenshot {


WebDriver driver;
String screenshotPath = "Your Path";


public void takeScreenshot() {
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_a");
Date date = new Date();
String date_time = dateFormat.format(date);
File file = new File(System.getProperty("user.dir") + File.separator
+ screenshotPath + File.separator + date_time);
boolean exists = file.exists();
if (!exists) {
new File(System.getProperty("user.dir") + File.separator
+ screenshotPath + File.separator + date_time).mkdir();
}


File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
String saveImgFile = System.getProperty("user.dir")
+ File.separator + screenshotPath + File.separator
+ date_time+ File.separator + "screenshot.png";
Reporter.log("Save Image File Path : " + saveImgFile, true);
FileUtils.copyFile(scrFile, new File(saveImgFile));
} catch (IOException e) {
e.printStackTrace();
}
}


public void takeScreenShotOnException(ITestResult result) {
String takeScreenshot = screenshotPath ;
if (result.getStatus() == ITestResult.FAILURE) {
Reporter.log(
"FAILURE occurred at "
+ DateUtil.converttimestamp(System
.currentTimeMillis()), true);
if (takeScreenshot.equalsIgnoreCase("true")
|| takeScreenshot.equalsIgnoreCase("yes")) {
try {
if (driver != null) {
takeScreenshot();
}
} catch (Exception ex) {
Reporter.log("Driver is null while taking screen shot",
true);
}
}
}
}


}


Call this java class in Test class:-

Test Class:-

@AfterMethod
public void snapshot(ITestResult result){
test.takescreenshot.takeScreenShotOnException(result);
}


Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home