Taking Screenshots with Selenium

The Problem:

You have some automated Selenium tests that you run periodically. Maybe these tests run as part of a continuous deployment process. Occasionally these tests will fail and you’ll find yourself analyzing error messages or stack traces that may or may not be very helpful. Wouldn’t it be nice to have some other tool available to help you with your debugging?

A Solution:

This solution provides a way of capturing screenshots of your browser, but only when your test fails. This way you don’t have a mess of screenshots to go through when its time to see why your test failed.

We are going to continue adding functionality to the project we created in the Selenium Hello World! post. We will be adding a new class FailureTasks. Place the class before the last squiggly bracket in Google.cs.

public class FailureTasks
{

}

Failure tasks will have two global variables, a webdriver and a function.

private IWebDriver _webDriver;
private Action<IWebDriver> _function;

Next, lets add the mechanism which actually takes the screenshot. In addition to the OpenQA.Selenium library. We will also need to import the System.IO and System.Drawing.Imaging libraries.

using System.IO;
using System.Drawing.Imaging;
public void SaveScreenshot() {
    Screenshot ss = 1)ITakesScreenshot)_webDriver).GetScreenshot();

    ss.SaveAsFile(
        Path.Combine(
            Environment.CurrentDirectory,
            string.Format("{0} - {1}.png",
                "Hello World",
                "Google",
            ImageFormat.Png);
}

Now, lets build the mechanism that takes the screenshot, but only when something in the _function global variable fails. This is done easily with a try-catch.

public void TakeScreenShot() {
    try {
        _function(_webDriver);
    }
    catch {
        SaveScreenshot();

        throw;
    }
}

The last thing we need for the FailureTasks class is a constructor.

public FailureTasks(IWebDriver webDriver, Action<IWebDriver> function)
{
    _webDriver = webDriver;
    _function = function;
}

We now have everything we need to take our screenshot. We just need to wrap the code in SearchForHelloWorld in a FailureTask object by using a lambda expression and tack on the TakeScreenShot method.

public void SearchForHelloWorld()
{
    IWebDriver webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
    new FailureTasks(webDriver, f =>
    {
        webDriver.Navigate().GoToUrl("http://www.google.com/");
        IWebElement textBox = webDriver.FindElement(By.Id("gbqfq"));
        textBox.SendKeys("Hello World!" + Keys.Enter);
        new WebDriverWait(webDriver, TimeSpan.FromSeconds(5)).Until<bool>(dr =>
        {
            try
            {
                IWebElement helpButton = dr.FindElement(By.XPath("//span[@id='fsl']/a"));
                Assert.AreEqual("Help", helpButton.Text);
                return true;
            }
            catch
            {
                return false;
            }
        });
    }).TakeScreenShot();
    webDriver.Dispose();
}

The test will now execute as it did before, but now, if the test fails, we will be able to find a screenshot of the browser at the time of failure in the HelloWorld project’s bin/Debug folder. You can make the test fail by removing its WebDriverWait.

Ninja Level

  • One of the things you can do to clean this up is to create a method that creates the FailureTasks object for you. If you do this, you can then use the screenshot mechanism like this:
webDriver.WhenThisFails(dr => {/*some function*/}).TakeScreenshot();

References   [ + ]

1. ITakesScreenshot)_webDriver).GetScreenshot(); ss.SaveAsFile( Path.Combine( Environment.CurrentDirectory, string.Format("{0} - {1}.png", "Hello World", "Google"

Leave a Reply

Your email address will not be published. Required fields are marked *