Road to capture screen shot of failed Webdriver test script part2

In my previous post ( "Road to capture screen shot of failed webdriver test script part1") I have posted how to capture screen shot using exception handling, but in this post I will show you how to capture screen shot by overriding testng listeners.

Here is code ( where I override onTestFailure,  onTestSuccess and onTestSkipped methods of class TestListenerAdapter.  Created function CaptureScreenShot and called it into onTestFailure function.

package com.webdriver.test;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class MyListner extends TestListenerAdapter{   
     public void onTestFailure(ITestResult result){ 
            System.out.println(result.getName()+" Test Failed \n");
     public void onTestSuccess(ITestResult result){
           System.out.println(result.getName()+" Test Passed \n");
     public void onTestSkipped(ITestResult result){
           System.out.println(result.getName()+" Test Skipped \n");
     public void CaptureScreenShot(ITestResult result){
           Object obj  = result.getInstance();
           WebDriver driver = ((FailedTestScreenCapture) obj).getDriver();
           File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
           try {
                  FileUtils.copyFile(scrFile, new File(“screenshot/” result.getName()+".png"));
           catch (IOException e) {

I called above created listeners java file in below “” TestNg file.

package com.webdriver.test;

import java.util.concurrent.TimeUnit;
import org.junit.Assert;
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.Listeners;
import org.testng.annotations.Test;

@Listeners ({MyListner.class})
public class FailedTestScreenCapture {
     protected WebDriver driver;
     protected String baseUrl;
     public WebDriver getDriver(){
              return driver;
     public void setUp() throws Exception {
              driver = new FirefoxDriver();                    
              baseUrl = "";
              driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     public void testCaptureScreen () {
           driver.get(baseUrl + "/");
           String title = driver.getTitle();
      public void tearDown() throws Exception {

Listeners “@Listeners ({MyListner.class})” added at class level. When run above test file. You should see that screen shot will capture and save into screenshot folder with same name as test name.
Below code is calling listeners using testing suite file.


Hope this will help you to capture screen shot of failed test.

No comments:

Post a Comment

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