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
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
Hitesh says
org.openqa.selenium.TakesScreenshot.getScreenshotAs(org.openqa.selenium.OutputType)” because “ts” is null
getting this error after run the testcase.
Mukesh Otwani says
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.
Hitesh Bali says
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.
Mukesh Otwani says
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.
Ramandeep says
can you share, how you resolved your issue ?
Mukesh Otwani says
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
could you please tell how this issue is resolved
Mukesh Otwani says
Hi Hitesh, please explain your query in detail.
Mahesh says
Hi ,
How to trigger the HTML test execution report automatically to or mailbox using maven and testng
Mukesh Otwani says
Hi Mahesh,
You can refer below links
https://learn-automation.com/send-report-through-email-in-selenium-webdriver/
Shiva says
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.
Mukesh Otwani says
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.
Rahul kumar says
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?
Mukesh Otwani says
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
Kishan Patel says
“import org.apache.commons.io.FileUtils;” is not being recognized in my program. Is there anything I would need to install?
Mukesh Otwani says
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/
Shruti says
Hi Mukesh,
Can you please provide the tutorial for taking screenshot for failed test cases using Listeners.
Mukesh Otwani says
Hi Shruti,
I’ll post it soon…:)
Surajsingh Rajput says
Hi Mukesh,
How can we capture screenshots for failed test cases only, by using iTestListener.
Mukesh Otwani says
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.
tejaswini says
hi..
can you tell us
about negative testing using selenium testNG
Mukesh Otwani says
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.
Mukesh Otwani says
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
Shivam Singh says
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.
Mukesh Otwani says
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.
Amit says
Hi Mukesh…
Can we use @AfterTest instead of @AfterMethod.
i think it will work in both annotations.
Mukesh Otwani says
Hi Amit,
This will work with AfterMethod only.
Tester Sweta says
I am getting “java.lang.NullPointerException” while trying to take screenshot. Please help me on this.
Mukesh Otwani says
Hi Sweta,
You are missing webdriver reference. Kindly check the code again.
Tester Sweta says
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.
Mukesh Otwani says
Great Sweta. Cheers
M Rakesh says
Hi Mukesh
How to take screen shots automatically when the test fails using JUnit?
Does JUnit support ITestResult interface?
Mukesh Otwani says
Hi Rakesh,
I am not good in JUnit.
Sowmya says
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
Mukesh Otwani says
not sure on Soumya. You can switch to TestNG from Junit its more useful.
getText says
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.
Mukesh Otwani says
Hey,
It seems some driver passing issue but without code cant guess the answer. Can you email your code mukeshotwani@learn-automation.com
kanchana says
Hi mukesh sir, when I am taking screenshot, it is coming in different font…… could you please help me in this issue?
Mukesh Otwani says
Hi Kanchana what do you mean by font? I did not get can you please explain.
Abhinav says
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.
Mukesh Otwani says
Hi Abhinav,
Its upto your logic to build the same. I wil suggest you to use BaseClass and put the screenshot login in @AfterMethod
jay says
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
Mukesh Otwani says
Hey jay kindly refer below post for email http://www.assertselenium.com/java/emailable-reports-for-selenium-scripts/
palani says
hi i have one problem how to record faliure selenium scripts tell me sir
Mukesh Otwani says
HI Palani,
Here is your solution http://learn-automation.com/how-to-capture-screenshot-for-failed-test-cases-in-selenium-webdriver/
Prashant says
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.
Mukesh Otwani says
Thanks Prashant 🙂 Keep in touch
Asif Mohammad says
Hai..bro..
I’m getting error while capturing screen shot at fail case in simple g-mail login functionality…
Mukesh Otwani says
Hey Asif,
What error u r getting kindly provide code as well.
Nikhil says
Thanks Mukesh learnt new thing today.
Mukesh Otwani says
Cheers Nikhil 🙂 Keep learning.
jay says
Can the report still run if I compiled it as a jar file?
Mukesh Otwani says
Yes jay it will work
Adrian says
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! 🙂
Mukesh Otwani says
Thanks Adrian
nikhil says
Nice code Mukesh , learned something new today.thank you!
Mukesh Otwani says
Thanks Nikhil 🙂
Adarsh says
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.
Mukesh Otwani says
HI Adarsh,
Ideally it should move to next code/testcase if any test fails.
Please cross check once again and let me know.
anoop says
unable to see the screenshots folder
Mukesh Otwani says
Hi Anoop,
Can u explain in brief?
sree says
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
Mukesh Otwani says
Hi Sree,
Same code will work for appium too. I have implemented in my org.
Amit Nagpal says
Thanks for this useful tutorial. It helped me a lot in enhancing my Framework.
Mukesh Otwani says
Hi Amit,
Thanks Keep visting 🙂
Sonia Sharma says
Thank you for this tutorial, i helped me to create good report into my automation framework tool.
Mukesh Otwani says
Hi Sonia,
Good to hear that Thanks 🙂 keep visiting.
Vinicius Lara says
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!
Mukesh Otwani says
`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