Software Testing Material

A site for software testers. We provide free online tutorials on Manual Testing, Automation Testing - Selenium, QTP, LoadRunner, Testing Tools and many more.

  • Blog
  • Tutorials
    • Manual Testing
    • Java
    • Selenium
      • TestNG
      • Maven
      • Jenkins
    • Framework
    • Katalon
    • Agile
    • SQL
    • VBScript
    • API Testing
  • Tools
    • TestLodge
    • FrogLogic GUI Tool
    • CrossBrowserTesting
    • BrowserStack
    • TestCaseLab
    • Kobiton
    • PractiTest
    • Sikuli
    • Postman
  • Interview Q & A
    • Selenium
    • TestNG
    • Test Framework
    • Explain Framework
    • Manual Testing
    • Software QA
    • Agile
    • Testing As A Career
    • General Interview Questions
    • API Testing
    • SOAP
    • JIRA
    • Protractor
  • Free Resources
  • Guest Post
    • Guest Post Guidelines
  • Training

How To Capture Screenshot of Failed Test Cases Using Selenium WebDriver

Last Updated on October 16, 2017 by Rajkumar

How To Capture Screenshot of Failed Test Cases Using Selenium WebDriver:

Earlier I have posted a detailed post on how to capture a screenshot using Selenium WebDriver. If you have missed it, you could check the detailed post on how to capture screenshot using Selenium WebDriver.

If a script fails, we need to know where was the error in script. Solution for this is to capture a screenshot of webpage when the test case fails. We could easily identify where exactly the script got failed by seeing the screenshot.

To achieve this, we could place the entire code in try-catch block. Which means placing the test steps in try block and screen capture statement in catch block. If a test step fails in the try block then it goes to the catch block and capture a screenshot of the web page.

Below mentioned script shows how to capture a screenshot of failed test cases using Selenium WebDriver.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package softwareTestingMaterial;
 
import java.io.File;
import org.apache.commons.io.FileUtils;
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;
 
public class CaptureScreenshot {
@Test
public static void captureScreenMethod() throws Exception{
                System.setProperty("webdriver.gecko.driver","D://Selenium Environment//Drivers//geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
        try{
            driver.get("https://www.softwaretestingmaterial.com");
    driver.navigate().refresh();
    //driver.findElement(By.xpath("//*[@id='cse-search-box']/div/input[4]")).sendKeys("agile"); //Statement with correct Xpath
    driver.findElement(By.xpath("//*[@id='cse']")).sendKeys("agile"); //Statement with incorrect Xpath
                }catch(Exception e){
            File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshotFile, new File("D:\\SoftwareTestingMaterial.png"));
}
        driver.close();
driver.quit();
}
}

Another way of capturing screenshot of failed test cases using Selenium WebDriver is to use ITestResult Interface.

ITestResult interface provides the test case execution status and test case name

We do place the screen capture steps in a separate method using AfterMethod TestNG Annotation. If we use TestNG AfterMethod annotation then this particular method (AfterMethod) executes after every test execution.

Below mentioned script shows how to capture a screenshot using ITestResult Interface.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package softwareTestingMaterial;
import java.io.File;
import org.apache.commons.io.FileUtils;
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 ScreenshotFailedCases {
// Create Webdriver reference
static WebDriver driver;
@Test
public static void captureScreenMethod() throws Exception{
System.setProperty("webdriver.gecko.driver","D://Selenium Environment//Drivers//geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.softwaretestingmaterial.com");
driver.navigate().refresh();
//driver.findElement(By.xpath("//*[@id='cse-search-box']/div/input[4]")).sendKeys("agile"); //Statement with correct Xpath
driver.findElement(By.xpath("//*[@id='cse']")).sendKeys("agile"); //Statement with incorrect Xpath
}
@AfterMethod //AfterMethod annotation - This method executes after every test execution
public void screenShot(ITestResult result){
//using ITestResult.FAILURE is equals to result.getStatus then it enter into if condition
if(ITestResult.FAILURE==result.getStatus()){
try{
// To create reference of TakesScreenshot
TakesScreenshot screenshot=(TakesScreenshot)driver;
// Call method to capture screenshot
File src=screenshot.getScreenshotAs(OutputType.FILE);
// Copy files to specific location
// result.getName() will return name of test case so that screenshot name will be same as test case name
FileUtils.copyFile(src, new File("D:\\"+result.getName()+".png"));
System.out.println("Successfully captured a screenshot");
}catch (Exception e){
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}
driver.quit();
}
}

If you are not regular reader of my blog then I highly recommend you to signup for the free email newsletter using the below link.

SUBSCRIBE TO GET FREE EBOOK AND REGULAR UPDATES ON SOFTWARE TESTING

Filed Under: Selenium

data-matched-content-rows-num="2" data-matched-content-columns-num="3"
Previous Article:
How To Capture Screenshot Using Selenium WebDriver
Next Article:
How To Capture Full Page Screenshot Using Selenium WebDriver

About the Author

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

Comments

  1. LDionisio says

    October 16, 2017 at 9:23 am

    in the first code box, you wrote “cactch” instead of catch in the try catch section.

    • Rajkumar says

      October 16, 2017 at 9:34 am

      Good catch LDionsio. Thanks. Have modified that.

  2. Shamsher Khan says

    December 18, 2017 at 8:35 pm

    Hi Rajkumar
    thanks a lot ur explanation is very useful for interview purpose

    • Rajkumar says

      December 19, 2017 at 1:05 am

      Thanks for your kind words Shamsher Khan

  3. rajkumar says

    February 9, 2018 at 6:38 am

    Hi raj,,

    when you are using ITestResult interface we need to implement that interface right…with out implementing interface can we directly use in screenshot method

    Thanks

    • Rajkumar says

      February 13, 2018 at 8:19 am

      We can use. I have mentioned two methods in the article.

ADVERTISEMENT

Froglogic-Squish-GUI-Tester
CrossBrowserTesting

TUTORIALS

  • Manual Testing Tutorial
  • Selenium Tutorial
  • TestNG Tutorial
  • VBScript Tutorial
  • Agile Methodology
  • SQL Tutorial for Testers
  • INTERVIEW QUESTIONS

  • Framework Interview Questions
  • Real Time Manual Testing
  • 100 Top Selenium Interview Questions
  • 30 Top TestNG Interview Questions
  • Agile Interview Questions
  • 80 SQL Interview Questions
  • TESTING TOOLS

  • Test Lodge
  • FrogLogic Squish
  • Cross Browser Testing
  • BrowserStack
  • Test Case Lab
  • Sikuli
  • © 2019 www.softwaretestingmaterial.com | About us | Privacy Policy | Contact us | Guest Post | Disclaimer | Terms of use | Sitemap