Quick Tip: Selenium – Taking screenshots (of regular tests and test failures)

The What

During Selenium test execution, i want to store a screenshot of what is displayed in the browser to understand in what conditions the test ran.

The How

Ideally you will create a screenshot capturing method that will be used across several tests. In the class where this will be created, the following classes need to be imported:

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

The first one of the two will define the type of object to which the screenshot will be stored (in this example, it will be saved to a file; a base64 string can also be used). The second import will be the one that creates the screenshot. The usage of these,  therefore taking a screenshot, is described below:

File filetoCopyTheScreenshot = new File(pathToFile);
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, filetoCopyTheScreenshot);

In the code above, the first line creates an empty file, to which the screenshot will be copied (it must be a location on the disk, with a file type of png). This happens because Selenium creates a screenshot (at the second line of the code above), however it deletes it after the test execution finishes. Therefore, it must be stored into the blank file created initially, as per the third line of code above.

So in this case, whenever the method into which the code above is defined gets called, a screenshot is created (the pathToFile must be created for each test run, otherwise the screenshot will be stored into just one file, meaning some screenshots will get overriden; therefore, the pathToFile should be sent as a parameter to the screenshot generating method).

Aditionally – take screenshots only on failures

In general you would only need to take a screenshot if a test has failed. To do so, you should put the screenshot taking code into a listener (remember this post about custom listeners), in the onTestFailure method), and maybe in the onTestSkipped one also (to better understand why a test was skipped). Just make sure that the tests that you need to take screenshots of are running having the listener dependency set.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s