How to take ScreenShot of failed test case using ITestResult interface in @AfterMethod annotation?

Taking Screen shot of all the test cases may create a memory issue, because we will be running the automation suite multiple times. Moreover, we can see the status of test cases (pass / failed / skipped) in the testing report. 
So, what is better is, to take the screen shot of only failed test cases.
To achieve this, we can use ITestResult interface in @AfterMethod annotation of testng.
ITestResult is an interface which keeps all information about test case which is being executed. It captures some information like Test case execution status, test case name etc
What we can do here is, in @AfterMethod annotation, get the status of the test using ITestResult Interface & check if it is failed. If failed then capture the screen shot. As simple as that.
Below Example Explains this.

package screenshotOfFailedTest;

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.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

public class CaptureScreenShotUsingITestResult {

WebDriver driver;

public void Testcase1(){

driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.findElement(By.xpath("ajhjhj")).click(); //take incorrect xpath, so that test will fail becuase element does not exist.


public void TearDown(ITestResult result) throws IOException{

if (result.getStatus() == ITestResult.FAILURE ){
TakesScreenshot ts = (TakesScreenshot)driver;
File srcFile = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("./ScreenShots/"+result.getName()+".jpg"));
//result.getname() method will give you current test case name.
//./ScreenShots/ tell you that, in your current directory, create folder ScreenShots. dot represents current directory


To know about how the same can be achieved using ITestListener, refer below post –
Hope This Helps!!!


Leave Comment

Your email address will not be published. Required fields are marked *

Looking for learning Framework Development from Scratch? Lookout for Detailed Framework Development videos on YouTube here -

Get the Framework code at Github Repo: