Capture Screen shot for failed Test cases in Selenium

Here we will learn how to capture the screen shots for the failed test cases in selenium. Screenshots are required to check why the test case fails and at what step test case fails so that we can debug the test case. we already covered the how to take screen shot in previous tutorial. Now we will modify the same code and learn how to take screenshots only when test cases failed and this is one of the most concept with respect to designing any framework.

Steps to take screen shot for failed test cases using ItestResult Interface.

1) Now we will create separate class “Library” and define the method “get_screen_shot” as in live projects we define the frequent use methods in a separate class. Refer how to take screen shot article to create screen shot method.
2) Create TestCase class and define two test cases , 1st Test case will pass and Second Test case will fail.( observe the program )
3) Create function with @AfterMethod annotation and pass the “ITestResult” object as parameter ( package – import org.testng.ITestResult is used ) and details are given in the program.
4) “get_screen_shot” method of library class is called only when the test case is failed.
5) Observe the below program , explanation is given in comments

Library class  – screen shot function is defined in this

package com.screenshotfailedcases;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class Library {

	// this function can be used to take screen shot 
	// by passing the driver as a parameter 
	public  static void get_screen_shot(WebDriver driver, String screenshot_name)
	{
	 
	// Convert webdriver object to Takescreenshot
	TakesScreenshot ts = ((TakesScreenshot)driver);
	// call get screen shot method and pass the parameter as file
	File src= ts.getScreenshotAs(OutputType.FILE);
	// date time stamp for unique screen shot name in milliseconds
	DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy hh-mm-ss.SSS");
    Date date = new Date();
    
	try {
	 // now copy the  screenshot to desired location using copyFile
	// we used relative path for screen shot 	
	FileUtils.copyFile(src, new File(".\\ScreenShots\\" + screenshot_name + dateFormat.format(date) + ".png"));
	}
	 
	catch (IOException e)
	 {
	  
		System.out.println(e.getMessage());
	 
	 }
	}

}

Test Class -> 3 Test cases are defined in this . 1st test case is passed , 2nd Test case is faile , 3rd Test case is skipped.

package com.screenshotfailedcases;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


public class TestCases {

 public WebDriver driver;

 // This test case is executed before class test cases started
 @BeforeClass
 public void open_Browser()
 {
 // Open Firefox
 System.setProperty("webdriver.gecko.driver", "geckodriver.exe"); 
 driver=new FirefoxDriver(); 
 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
 driver.manage().window().maximize();
 System.out.println("Test case execution started");
 }
 
 // This test case will pass
 @Test
 public void Verify_Google_Title()
 {
 
 driver.get("https://www.google.co.in/");
 String actual_Title= driver.getTitle();
 String expected_Title ="Google";
 // this test case will pass
 Assert.assertEquals(actual_Title, expected_Title);
 }
 
 // This test case will fail
 @Test
 public void Verify_Yahoo_Title()
 { 
 driver.get("https://in.yahoo.com/");
 String actual_Title= driver.getTitle();
 String expected_Title ="Google";
 // this test case will fail as expected is google and actual is yahoo
 Assert.assertEquals(actual_Title, expected_Title);
 }
 
 // This test case is skipped
 @Test
 public void Verify_skip_Title()
 { 
 throw new SkipException("Test case is skipped");
 }
 
 // This test case is executed after each test case
 @AfterMethod
 public void Check_Status(ITestResult result)
 {
 // check whether test case fails or not 
 // if Test case fails
 if (result.getStatus() == ITestResult.FAILURE)
 {
 // Take screen shot
 Library.get_screen_shot(driver,result.getName());
 System.out.println(result.getName() + " is failed");
 }
 // if test case is passed
 else if(result.getStatus()==ITestResult.SUCCESS){
 System.out.println(result.getName() + " is passed");
 System.out.println("---------------");
 }
 // if test case is skipped
 else{
 System.out.println(result.getName() + " is skipped");
 System.out.println("---------------");
 }
 
 }
 
 // This test case is executed after class
 @AfterClass
 public void Close_Browser()
 {
 driver.quit();
 System.out.println("Test case execution stopped");
 }
}

Output : execute the above TestCases class as TestNg

-------------------
Test case execution started
Verify_Google_Title is passed
---------------
Verify_Yahoo_Title is failed
Verify_skip_Title is skipped
---------------Test case execution stopped

===============================================
Suite
Total tests run: 3, Failures: 1, Skips: 1
===============================================

Note : Screen shot is captured only for failed test case that is Verify_Yahoo_Title. See the screen shot below.

screenshot-for-failes-test-cases

This is all about how we can take screenshots for the failed test cases only. If you have any question regarding this please leave in below comments.