How to capture test case screenshot with selenium webdriver

We all know it is very helpful to capture screenshot for test cases, especially for failed test cases. It is also very helpful for developer or tester to identify and debug bugs when seeing screenshot besides exception messages. We can benefit from following points.

1.Check why the test case failed.
Failed because of selenium script issue such as web element locator changed, we should update our selenium script in this case.
Failed due to program coding issue, we should provide developer or tester with the screenshot to help them to investigate.
2.Make a better understanding for the application’s flow and check whether the test case behaved correctly or not.
With screenshot, you can easily know which page should be shown after login action for a system, whether the page is correct or not. You can also know which condition will direct user to a reset password page or to a login error page. You will be more clear with each step in test cases.
3.Helpful when run test cases across multiple browsers(Firefox, Chrome, IE).
As you know, test case runs different across multiple browsers especialy the web ui part. With screenshot, you can see the difference between multiple browsers more directly. You can save a lot of time and efforts.
4.Track test execution process when run test cases using Headless web browser.
Test cases will run more quickly and less resource consumption with headless web browser. You can capture the key screenshot when run test cases in headless browser to verify the test execute process.

How to catch screenshot using selenium webdriver
We can do this with following java code in selenium.
1. Initiate Firefox webdriver instance. Maxmize Firefox browser and get webpage.

 WebDriver driver = new FirefoxDriver();

2. Use TakesScreenshot class’s getScreenshotAs method to get the source file.
And the use FileUtils class’s copyFile method to save it to a destination file.

 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
 //save screenshot to C:\\Workspace\\\\Images\\screenshot.png
 FileUtils.copyFile(scrFile, new File("C:\\Workspace\\\\Images\\screenshot.png"));

 With above java code, you can take screentshot for web page and save it to file C:\\Workspace\\\\Images\\screenshot.png.

But how can you take multiple screen shot in test cases, you can incapsulate above code into a method and call the method multiple times when you need to take a screen shot. You can download the example source code at the end of this post.

[download id=”223″]

0 0 vote
Article Rating
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x