Screenshots with Java

While puting together some tests using Selenium I found that sometimes, you just need a person to look at a page to see if its "right".


July 14, 2008: It looks like the feature has been added to selenium. More info in the resources. Read-on if you need screenshots for other purposes.

Making testers click through a site is tedious and error prone. My solution was to tak screenshots while navigating with selenium. The screen shots get dumped into a directory. Later, the testers can just page through the images very quickly.

The code for taking a screenshot is pretty simple. It shouldn't need any explanation. If anything is unclear, the javadocs for the classes used should clear things up.

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public void captureScreen(String fileName) throws Exception {
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));

My recommendation is to name the file after the test case being run. If there are multiple navigations, append the test name with the condition expected. This can help testers communicate the issue much better.

Another use for screenshots; attaching a screenshot to a bug report can really help communicate problems to the developers who will need to fix them.


I discovered from a DZone user, Bort1002000 That as of version 0.92 of Selenium RC that the feature has been added.

Here's the javadoc for Selenium.captureScreenshot.

He provided a link to a blog post demonstrating using Maven, jUnit, and Selenium. Here are translations using bablefish and Google Language Tools.

-- Paul

Tech Tags:


About willCode4Beer