Road to capture screen shot of failed Webdriver script part1

In this post I will show you how to capture screen shot of failed test using exception handling and test marked failed in report.
In below example I handle exception using try catch block and call capture screen shot function in catch section, then throws exception make test fail.
package com.webdriver.test;

import java.util.concurrent.TimeUnit;
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.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

public class MyClass {
private WebDriver driver;
private String baseUrl;

      public void setUp() throws Exception {
            driver = new FirefoxDriver();
            baseUrl = "";
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      public void testCaptureScreenShot() throws Exception {
                 driver.get(baseUrl + "/"); 
                 driver.findElement(By.cssSelector("#gb_2 > span.fffgbts")).click();
                 driver.findElement(By.cssSelector("#gb_1 > span.gbt")).click();                        
            catch(Exception ex){
                  throw ex;
            catch(Error ex){
                  throw ex;
      public void captureScreenShot(String name) throws IOException{
            File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(file, new File(name+".jpg"));

      public void tearDown() throws Exception {


Execute above test and you should see “testCaptureScreenShot.jpg” image will generate at root folder of your project.

No comments:

Post a Comment

Leave your comments, queries, suggestion I will try to provide solution