Capturing Web Page Screenshots with Selenium 2

There have been many times when I have run a Unit Test that has failed and afterwards I wondered where it went wrong. The ability to see what occurred on the page or how it looked at the time would be a great benefit. I've been writing a few automated tests lately and looking for a way to implement this functionality. Luckily, Selenium 2 provides easy functionality that allows you to capture a screenshot of the page at the time that a unit test is being run - and it's really easy too.

Selenium WebDriver

If you aren't really familiar with Selenium 2, please check out another post I wrote that provides a simple guide to getting started with Selenium. There is also quite a few resources available on the Google code site.

Right, let's get started. I am going to create a simple example that checks if the page has redirected to a different page and if so, we save a screenshot of the page. Once you have added references to the Selenium 2 and Nunit we need to declare our driver. For this instance I am using the FirefoxDriver - You could also test this using the other drivers that come with Selenium 2, for example IE and Chrome.

Selenium

Then write the unit test that we will use and check if an error is thrown.

Selenium

Let's break this down.

  1. Navigate to the URL that we think will throw an error.
  2. Check if the current URL matches the URL that we originally navigated to.
  3. If the current Url and the original URL doesn't match we call the method SaveScreenShot.
  4. Finally, we fail the test.

Here is the method that we use to save the screenshot.

Selenium WebDriver Screenshot

Let's break this method down a little further.

  1. First, we use the FireFoxDriver to get the screenshot for us.
  2. Next I am building up a unique file name based on the current date and time, you could change this to anything.
  3. Then save the image.

This is a very simple example and would definitely need to be expanded on in a real world situation. However, there are so many usages that this little function can be applied to. If you wanted you could also save a log file with the details of the unit tests and the reasons for failure. There is also the possibility of forwarding on an email with an attached screenshot when the test fails.

I have also included a sample project that is available for download. It contains the example in this post as well as the original examples that were contained in my other Selenium 2 article.

Hope this helps!