Thursday, October 9, 2014

Screenshot using Selenium WebDriver

Well many times in Automation Testing Scenario, Script and Test Case is failing due to object not found. It is handle in many testing tools in different languages. In this post, I will show you how to capture screen shot of failed test using @AfterMethod and test marked failed in report. In below example, I have handle a function with @AfterMethod annotation to capture the Screenshot using in Selenium Web Driver. To capture the Screenshot using selenium Web Driver, If you are using testNG, you can add the listener class which will further be extended with 'TestListenerAdapter' which has the implementation of taking screenshot on failures. This way we need not to make any logic change to take screenshot all the time.


Example 1:
@AfterMethod(alwaysRun = true, description = "take screenshot")
public void afterMethod_takeScreenshot(ITestResult result, Method m) throws Exception {
if (!result.isSuccess()) {
TakesScreenshot screen = (TakesScreenshot) driver;
File fileScreen = screen.getScreenshotAs(OutputType.FILE);
File fileTarget = new File("failure_" + m.getName() + ".png");
FileUtils.forceMkdir(fileTarget.getParentFile());
FileUtils.copyFile(fileScreen, fileTarget);
}

Example 2:
@AfterMethod
public void onTestFailure(ITestResult result) {

if(!result.isSuccess()){
String workingDirectory = System.getProperty("user.dir");
//specify ur path of screenshots folder here
String fileName = workingDirectory + File.separator +"screenshots"+ File.separator + result.getMethod().getMethodName() + "().png";//filename
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(fileName ));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}