• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Programming Languages
    • Java Tutorials
    • Python Tutorials
    • JavaScript Tutorials
  • Automation Tools and Different Tools
    • Web Automation
      • Selenium with Java
        • Selenium Basic
        • Selenium Advance
        • Selenium Realtime
        • Framework
        • Selenium Interview
        • Selenium Videos
        • Selenium with Docker
      • Selenium with Python
      • WebdriverIO
        • Selenium Webdriver C# Tutorial
      • Cypress
      • Playwright
    • TestNG
    • Cucumber
    • Mobile Automation
      • Appium
    • API Testing
      • Postman
      • Rest Assured
      • SOAPUI
    • testRigor
    • Katalon
    • TestProject
    • Serenity BDD
    • Gradle- Build Tool
    • RPA-UiPath
    • Protractor
    • Windows Automation
  • Automation For Manual Testers
  • Services
  • Online Training
  • Contact us
  • About me
  • Follow us
    • Linkedin
    • Facebook Group
    • Facebook Page
    • Instagram

Automation

Selenium WebDriver tutorial Step by Step

You are here: Home / Advance Selenium / How to capture screenshot for failed test cases in Selenium Webdriver

How to capture screenshot for failed test cases in Selenium Webdriver

February 20, 2021 by Mukesh Otwani 69 Comments

Takes screenshot on failure in Selenium WEbdriver

Writing Selenium Webdriver script is not enough everyone can design a script nowadays. We need to design the script in such a way that we can utilize script code as much as possible. This article will talk about the Capture screenshot in selenium for failed test cases.

I am a big fan of screenshots in Automation because it helps me a lot to identify the exact issue.

Generally, scripts fail in 2 situations.

1-If script has some issue (some locator has been changed or application has some changes)- In this case, we need to maintain our Selenium script.

2-Due to application issue- In this case, we need to inform to respective point of contact (Manual Tester or Developer)

How to Capture screenshot in selenium for failed test cases

Previously I have covered a post on capture screenshot in Selenium so if you have not gone through the previos post then I will highly recommend you to please go through the post and youtube as well.

https://learn-automation.com/how-to-capture-screenshot-in-selenium-webdriver/

Today we will see something different How to capture a screenshot for failed test cases in Selenium Webdriver.

Here I will be using two new topics which will help us to achieve the same.

1-We will use ITestResult Interface which will provide us the test case execution status and test case name.

Please refer official doc for ITestResult

2- @AfterMethod is another annotation of TestNG that will execute after every test execution whether test case pass or fail @AfterMethod will always execute.

Please refer official doc for @AfterMethod

If you are new to TestNG and want to explore more on TestNG then I will recommend you to please go through the below TestNG topics.

I have covered a couple of topics for TestNG. You can check all TestNG Tutorial here

Now let’s get started and will see through a complete program.

 

If you want to refer to video for the same then refer to the YouTube video

 

Program to Capture screenshot in selenium for failed test cases

// Create a package in eclipse
package captureScreenshot;

// Import all classes and interface
import java.io.File;
import library.Utility;
import org.openqa.selenium.io.FileHandler;
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 FacebookScreenshot {

// Create Webdriver reference
WebDriver driver;

@Test
public void captureScreenshot() throws Exception
{

// Initiate Firefox browser
driver=new FirefoxDriver();

// Maximize the browser
driver.manage().window().maximize();

// Pass application url
driver.get("http://www.facebook.com");

// Here we are forcefully passing wrong id so that it will fail our testcase
driver.findElement(By.xpath(".//*[@id='emailasdasdas']")).sendKeys("Learn Automation");


}





// It will execute after every test execution 
@AfterMethod
public void tearDown(ITestResult result)
{

// Here will compare if test is failing then only it will enter into if condition
if(ITestResult.FAILURE==result.getStatus())
{
try 
{
// Create refernce of TakesScreenshot
TakesScreenshot ts=(TakesScreenshot)driver;

// Call method to capture screenshot
File source=ts.getScreenshotAs(OutputType.FILE);

// Copy method  specific location here it will save all screenshot in our project home directory and
// result.getName() will return name of test case so that screenshot name will be same
try{
FileHandler.copy(source, new File("./Screenshots/"+result.getName()+".png"));
System.out.println("Screenshot taken");
}
} 
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
} 
}
// close application
driver.quit();
}



}

The above code will execute fine and if the test case will fail it will capture the screenshot. Check below screenshot

Capture screenshot in selenium for failed test cases

 

The above code is fine but still, we need to enhance our code so that we can reuse it.

We will create a Utility class that will have one method which will capture the screenshot.

Code to create a method for screenshot

package library;

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

public class Utility 
{
public static void captureScreenshot(WebDriver driver,String screenshotName)
{

try 
{
TakesScreenshot ts=(TakesScreenshot)driver;

File source=ts.getScreenshotAs(OutputType.FILE);

FileHandler.copy(source, new File("./Screenshots/"+screenshotName+".png"));

System.out.println("Screenshot taken");
} 
catch (Exception e)
{

System.out.println("Exception while taking screenshot "+e.getMessage());
} 
}
}

 

You call the above method in the below format

Utility.captureScreenshot(driver,"name of screenshot");

 

Hope the above article will help you in the Interview or in your automation test framework.

Comment below if any queries or suggestions or Feedback.

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

Filed Under: Advance Selenium, sticky Tagged With: screenshot only for failed test cases in Selenium

Reader Interactions

Comments

  1. Hitesh says

    February 24, 2021 at 2:33 PM

    org.openqa.selenium.TakesScreenshot.getScreenshotAs(org.openqa.selenium.OutputType)” because “ts” is null

    getting this error after run the testcase.

    Reply
    • Mukesh Otwani says

      February 24, 2021 at 4:14 PM

      Hi Hitesh, please share the code to email mukeshotwani@learn-automation.com
      Null pointer exception is very common java exception which is because variable have null value.

      Reply
      • Hitesh Bali says

        March 1, 2021 at 4:45 PM

        Hi Mukesh,

        Actually that issue has resolved now but its i am running multiple users via excel and the testcases are depends on that users. So the issue is i am getting only single screenshot of failed testcase which is running in the last.

        Reply
        • Mukesh Otwani says

          March 2, 2021 at 2:27 PM

          Hi Hitesh,

          Please share your code because scenario which you have mentioned here is understandable but there is no information about how your framework configured. You need to check your framework thoroughly.

          Reply
        • Ramandeep says

          March 26, 2021 at 2:39 AM

          can you share, how you resolved your issue ?

          Reply
          • Mukesh Otwani says

            March 26, 2021 at 8:05 PM

            Hi Ramandeep,

            If you are also facing the same issue then you need to have screenshots name dynamically like adding some timestamp in filename.

        • basit says

          July 6, 2022 at 6:43 PM

          could you please tell how this issue is resolved

          Reply
          • Mukesh Otwani says

            July 22, 2022 at 1:08 PM

            Hi Hitesh, please explain your query in detail.

  2. Mahesh says

    October 20, 2020 at 1:43 PM

    Hi ,

    How to trigger the HTML test execution report automatically to or mailbox using maven and testng

    Reply
    • Mukesh Otwani says

      October 21, 2020 at 3:54 PM

      Hi Mahesh,

      You can refer below links
      https://learn-automation.com/send-report-through-email-in-selenium-webdriver/

      Reply
  3. Shiva says

    September 6, 2019 at 12:38 PM

    Hi Mukesh Greetings & my best wishes.
    Can we do the same in C# as well?
    If yes, could you please do a video or write a blog on the same.

    Reply
    • Mukesh Otwani says

      September 6, 2019 at 2:36 PM

      Hi Shiva,

      You can use OnException method from EventFiringWebDriver class where you can inject screenshot taking mechanism. Link is here
      I’ll plan one video on this topic too.

      Reply
  4. Rahul kumar says

    July 30, 2019 at 12:27 AM

    Hi Mukesh,
    Is there any prerequisite for this screenshot code, saying so, Do we need any specific version of Apache POI of testng for this code?

    Reply
    • Mukesh Otwani says

      July 30, 2019 at 9:58 AM

      Hi Rahul,

      Apache POI is to deal with Microsoft Documents like Word, Excel, Powerpoint etc. Moreover TestNG and Apache POI don’t share any dependency with each other. Screenshot mechanism is nowhere dependent on TestNG and Apache POI

      Reply
  5. Kishan Patel says

    July 24, 2019 at 11:08 PM

    “import org.apache.commons.io.FileUtils;” is not being recognized in my program. Is there anything I would need to install?

    Reply
    • Mukesh Otwani says

      July 25, 2019 at 11:06 AM

      Hi Kishan,

      You can use FileHandler class. For more details, please check this link http://learn-automation.com/how-to-use-filehandler-class-in-selenium-for-screenshot/

      Reply
  6. Shruti says

    July 3, 2019 at 2:43 PM

    Hi Mukesh,
    Can you please provide the tutorial for taking screenshot for failed test cases using Listeners.

    Reply
    • Mukesh Otwani says

      July 3, 2019 at 10:40 PM

      Hi Shruti,

      I’ll post it soon…:)

      Reply
  7. Surajsingh Rajput says

    May 9, 2019 at 12:53 PM

    Hi Mukesh,
    How can we capture screenshots for failed test cases only, by using iTestListener.

    Reply
    • Mukesh Otwani says

      May 9, 2019 at 8:27 PM

      Hi Surajsingh,

      Using ITestListner interface, it provides a method called onTestFailure() where you can call screenshot taking mechanism. This method will be called on whenever any test method fails.

      Reply
  8. tejaswini says

    April 2, 2019 at 11:25 AM

    hi..
    can you tell us
    about negative testing using selenium testNG

    Reply
    • Mukesh Otwani says

      April 2, 2019 at 2:29 PM

      Hi Tejaswini,

      Using dataProvider, provide wrong credentials for any application login and verify error message for each set of credentials. Please check this link http://learn-automation.com/data-driven-framework-in-selenium-webdriver/ for better understanding. But I would suggest that negativce testing for UI is not recommendable.

      Reply
    • Mukesh Otwani says

      April 2, 2019 at 2:31 PM

      Hi Tejaswini,

      Using dataProvider, provide wrong credentials fro any application login and verify error message for each set of credentials. Please check this link http://learn-automation.com/data-driven-framework-in-selenium-webdriver/ for better understanding

      Reply
      • Shivam Singh says

        May 13, 2019 at 3:28 PM

        Hi Mukesh,

        Just wanted to ask that how can we add and capture all screenshots for all credentials sent using data driven frame work in extent report.

        Reply
        • Mukesh Otwani says

          May 13, 2019 at 6:39 PM

          Hi Shivam,

          Just call ExtentTest object soon after passing credentials. Since credentials passing sequence will keep on repeating that much number of times screenshot along with ExtentTest statement will be called off.

          Reply
  9. Amit says

    December 16, 2016 at 5:42 PM

    Hi Mukesh…

    Can we use @AfterTest instead of @AfterMethod.
    i think it will work in both annotations.

    Reply
    • Mukesh Otwani says

      December 17, 2016 at 11:55 AM

      Hi Amit,

      This will work with AfterMethod only.

      Reply
  10. Tester Sweta says

    November 28, 2016 at 5:26 PM

    I am getting “java.lang.NullPointerException” while trying to take screenshot. Please help me on this.

    Reply
    • Mukesh Otwani says

      November 28, 2016 at 11:29 PM

      Hi Sweta,

      You are missing webdriver reference. Kindly check the code again.

      Reply
      • Tester Sweta says

        November 29, 2016 at 4:25 PM

        Hi Mukesh,
        I am able to make my code workable. I was initializing webdriver within @Test method as well which was giving me problem. Thank you for this video.

        Reply
        • Mukesh Otwani says

          November 30, 2016 at 8:07 PM

          Great Sweta. Cheers

          Reply
  11. M Rakesh says

    November 23, 2016 at 1:35 AM

    Hi Mukesh
    How to take screen shots automatically when the test fails using JUnit?
    Does JUnit support ITestResult interface?

    Reply
    • Mukesh Otwani says

      November 23, 2016 at 1:22 PM

      Hi Rakesh,

      I am not good in JUnit.

      Reply
  12. Sowmya says

    November 7, 2016 at 6:28 PM

    Hi Mukesh,
    Hope you are well, Thanks for your videos and they are very helpful.
    I am using jUnit framework, is there any interface equivalent to ITestResult in jUnit. Thanks

    Reply
    • Mukesh Otwani says

      November 30, 2016 at 7:58 PM

      not sure on Soumya. You can switch to TestNG from Junit its more useful.

      Reply
  13. getText says

    September 28, 2016 at 5:54 PM

    Hi Mukesh,

    I want to able to take screenshots of failed tests. I have a TestBase Class and a PageBase class. I called the captureScreenshot method in the TestBase class inside the @AfterMethod but it does not seem to work and throws a NullPointerException.

    Although when I use the same method code on it’s own it works fine. Can you help please? I am using PageObject Design pattern and running my tests from a testng.xml file. Thanks a lot.

    Reply
    • Mukesh Otwani says

      September 29, 2016 at 10:40 AM

      Hey,

      It seems some driver passing issue but without code cant guess the answer. Can you email your code mukeshotwani@learn-automation.com

      Reply
  14. kanchana says

    September 9, 2016 at 9:32 PM

    Hi mukesh sir, when I am taking screenshot, it is coming in different font…… could you please help me in this issue?

    Reply
    • Mukesh Otwani says

      September 12, 2016 at 3:43 PM

      Hi Kanchana what do you mean by font? I did not get can you please explain.

      Reply
  15. Abhinav says

    September 7, 2016 at 2:44 PM

    Hi Mukesh

    I ahve taken the screen shot of the failed test case and stored in a folder in C Drive. Now I want to attach this file in the reports but I want to generalize the method means for each test case it should check if it is failed or passed if failed it should attach the image of the failed test case.

    Reply
    • Mukesh Otwani says

      September 7, 2016 at 11:44 PM

      Hi Abhinav,

      Its upto your logic to build the same. I wil suggest you to use BaseClass and put the screenshot login in @AfterMethod

      Reply
  16. jay says

    September 2, 2016 at 1:25 PM

    Hi Mukesh,

    I know this is out of the topic, but I would like to ask if there is a way to generate the extent reports to be attached to the email body message

    Reply
    • Mukesh Otwani says

      September 2, 2016 at 5:33 PM

      Hey jay kindly refer below post for email http://www.assertselenium.com/java/emailable-reports-for-selenium-scripts/

      Reply
  17. palani says

    September 1, 2016 at 11:46 AM

    hi i have one problem how to record faliure selenium scripts tell me sir

    Reply
    • Mukesh Otwani says

      September 2, 2016 at 5:59 PM

      HI Palani,

      Here is your solution http://learn-automation.com/how-to-capture-screenshot-for-failed-test-cases-in-selenium-webdriver/

      Reply
  18. Prashant says

    August 31, 2016 at 12:05 AM

    Hey Mukesh,

    You are not only the brilliant…. you are the Extra Brilliant. Means, what’s the way of your teaching!!!! You are the superb man…… Keep teaching….. Keep rocking.

    Reply
    • Mukesh Otwani says

      September 8, 2016 at 12:19 AM

      Thanks Prashant 🙂 Keep in touch

      Reply
  19. Asif Mohammad says

    August 25, 2016 at 6:16 PM

    Hai..bro..
    I’m getting error while capturing screen shot at fail case in simple g-mail login functionality…

    Reply
    • Mukesh Otwani says

      August 27, 2016 at 10:32 PM

      Hey Asif,

      What error u r getting kindly provide code as well.

      Reply
  20. Nikhil says

    August 15, 2016 at 5:10 PM

    Thanks Mukesh learnt new thing today.

    Reply
    • Mukesh Otwani says

      August 18, 2016 at 9:46 AM

      Cheers Nikhil 🙂 Keep learning.

      Reply
  21. jay says

    August 4, 2016 at 2:06 PM

    Can the report still run if I compiled it as a jar file?

    Reply
    • Mukesh Otwani says

      August 5, 2016 at 11:33 AM

      Yes jay it will work

      Reply
  22. Adrian says

    June 9, 2016 at 5:56 PM

    Nice tutorial, but you got typo in ULR to
    “Please refer official doc for ITestResult”
    Correct url is: http://testng.org/javadocs/org/testng/ITestResult.html
    Cheers! 🙂

    Reply
    • Mukesh Otwani says

      June 14, 2016 at 9:18 PM

      Thanks Adrian

      Reply
  23. nikhil says

    April 22, 2016 at 9:48 PM

    Nice code Mukesh , learned something new today.thank you!

    Reply
    • Mukesh Otwani says

      April 26, 2016 at 5:39 PM

      Thanks Nikhil 🙂

      Reply
  24. Adarsh says

    March 21, 2016 at 1:08 PM

    Hi Mukesh I have implemented your and it is taking the screenshot but i have created 10 testcases and i am making 4th test case to fail but it is not moving to the next test case please help me.

    Reply
    • Mukesh Otwani says

      March 26, 2016 at 2:08 PM

      HI Adarsh,

      Ideally it should move to next code/testcase if any test fails.

      Please cross check once again and let me know.

      Reply
  25. anoop says

    March 1, 2016 at 8:11 PM

    unable to see the screenshots folder

    Reply
    • Mukesh Otwani says

      March 1, 2016 at 11:58 PM

      Hi Anoop,

      Can u explain in brief?

      Reply
  26. sree says

    February 11, 2016 at 12:51 PM

    Thanks for the tutorial, i wants to implement failed test screencapture for appium ios and android tests on real devices.
    please guide me.
    regards
    sree

    Reply
    • Mukesh Otwani says

      March 3, 2016 at 4:49 PM

      Hi Sree,

      Same code will work for appium too. I have implemented in my org.

      Reply
  27. Amit Nagpal says

    November 4, 2015 at 6:19 PM

    Thanks for this useful tutorial. It helped me a lot in enhancing my Framework.

    Reply
    • Mukesh Otwani says

      November 5, 2015 at 1:29 AM

      Hi Amit,

      Thanks Keep visting 🙂

      Reply
  28. Sonia Sharma says

    October 30, 2015 at 12:01 PM

    Thank you for this tutorial, i helped me to create good report into my automation framework tool.

    Reply
    • Mukesh Otwani says

      October 30, 2015 at 11:20 PM

      Hi Sonia,

      Good to hear that Thanks 🙂 keep visiting.

      Reply
  29. Vinicius Lara says

    October 22, 2015 at 5:42 PM

    Thanks for this great tutorial.
    It helped me a lot!

    But I have a problem:
    I’ve created a class separated to my test class and I don’t know how can I
    set the TestResult status on my test class.
    Should I set this property on every test method on my test class?

    Thanks a lot!

    Reply
    • Mukesh Otwani says

      October 26, 2015 at 7:46 AM

      `Hi Vinicius Lara,

      Sorry for late reply I was out of town.

      I will explain you how we categorize our test.

      1- Create java class which can contain multiple test

      2- Create an xml file which will execute above test and run this xml

      3- If you have multiple xml then you can run through cmd or batch file as well.

      Hope its clear let me know if you need more details I will share the links too.

      Thanks
      Mukesh

      Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Free Selenium Videos

https://www.youtube.com/watch?v=w_iPCT1ETO4

Search topic

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?

Stay connected via Facebook

Stay connected via Facebook

Archives

Footer

Categories

Recent Post

  • API Testing Using Postman And RestAssured
  • Disable Personalise Your Web Experience Microsoft Edge Prompt In Selenium
  • How To Fix Error: No tests found In Playwright
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Best and easy way to Group test cases in selenium

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?