February 25, 2014

Screenshot on Failure using Selenium WebDriver

Below post explains how to capture screenshot when scripts fails using Selenium WebDriver.

Capturing screen shot if script fails is absolutely necessary to understand the problem.


In the below script we have used simple try Catch & Finally blocks. If any error occurs in try block control will go to catch block.

In Catch block We have written code for capturing screenshot and flag is set to true.
If the flag is true then finally block statement will be executed.

In Finally block  We have written exception that will raise an exception so that you can see the results if the script as failure. 



package sample;
 
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
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.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
 
public class Screenshotonfailure{
    public WebDriver driver;
    boolean flag = false;
  @Test
  public void f() throws Exception {
      try {
          driver.get("http://www.bing.com");
          driver.findElement(By.id("search123")).sendKeys("123456");
    } catch (Exception e) {
         File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            // Now you can do whatever you need to do with it, for example copy somewhere
            FileUtils.copyFile(scrFile, new File("C:\\Naga\\Jar\\screenshot.png"));
            flag = true;
    }
      finally
      {
          if(flag)
          {
              throw new NoSuchElementException("Element not found");
          }
      }
  }
  @BeforeClass
  public void beforeClass() {
      driver = new FirefoxDriver();
  }
  @AfterClass
  public void afterClass() throws Exception {
      driver.quit();
  }
}

3 comments: