Saturday 15 November 2014

Taking Screenshot using Selenium Webdriver

Selenium Webdriver provides functionality to capture screenshot at run time. It can be very useful if it is implemented in a right ways in your framework. Suppose we have to capture screenshot at run time whenever any validation is failed. It will also help non technical person to understand the reason behind of the failure and will help tester/developer to debug in less time.

In the below example code we are providing wrong value of Sign In button to fail the test, and based on the Boolean result driver is capturing the screenshot.

Find the sample code below for the same:


import java.net.MalformedURLException;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class CaptureScreenshot {
 
public WebDriver driver;
boolean flag1;

 @BeforeClass
 public void setup(){
  driver = new FirefoxDriver();
  driver.get("http:\\www.gmail.com");
 }
 
 @Test
 public void testOne(){
         flag1 = driver.findElement(By.id("signIn")).getAttribute("value").
                 equalsIgnoreCase("Sign");
 }
 
 @AfterMethod
 public void afterFailure(){
  try {
   captureScreen(uniqueFileName(), flag1);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public void captureScreen(String fileName, boolean flag) throws IOException{
  if(flag == false){
   File scrFile = ((TakesScreenshot) driver).getScreenshotAs(
                  OutputType.FILE);
   FileUtils.copyFile(scrFile, new File(fileName),true);
  }else{
   System.out.println("Validation Passed");
  }
  
 }
 
 public String uniqueFileName(){
  String imageName = "C:\\SeleniumImage\\Image" + UUID.randomUUID().
                      toString().replaceAll("-", "") + ".png";
  System.out.println(imageName);
  return imageName;
 }
 
 @AfterClass
 public void tearDown(){
  driver.quit();
 }
}

Stay tuned to see more updates.

Facebook Page: https://www.facebook.com/crazzzygig