Taking screenshots of a test failures using Selenium
WebDriver can come in handy, especially when investigating failed test cases
from previous test executions. For example, a test that may have ran overnight.
Screenshots coupled with the stack trace and logging allows you to
diagnose why a test failed without the need to rerun the test.
In the solution below I will detail how to take a screenshot using Selenium WebDriver, with the following caveats;
- I am
not sure what test may fail, so I cannot explicitly set what tests should take a
screenshot.
- I do
not want to capture a screenshot of successful test runs.
To get around this problem I will be taking advantage of
NUnit's TestContext which contains a wealth of useful information. For
example, the full name and status of a test.
Tips:
Ensure you edit the location for the screenshot file as you
see fit.
[C#]
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Diagnostics;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace TestAutomationEngineer
{
[TestFixture]
public class Screenshots
{
private IWebDriver driver;
private string baseURL;
private string filename;
private string saveLocation;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://testautomationengineer.blogspot.co.uk/";
}
[TearDown]
public void TeardownTest()
{
if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
{
Snap(driver);
Console.WriteLine("Check out why the test failed, look here: " + filename);
}
if(driver != null)
{
driver.Quit();
}
}
[Test]
public void TakeScreenshotTestThatPasses()
{
driver.Navigate().GoToUrl(baseURL);
Assert.IsTrue(true);
}
[Test]
public void TakeScreenshotTestThatFails()
{
driver.Navigate().GoToUrl(baseURL);
Assert.IsTrue(false);
}
public void Snap(IWebDriver driver)
{
try{
createTempDirectory();
createFilename();
((ITakesScreenshot) driver).GetScreenshot().SaveAsFile(filename, ImageFormat.Png);
}
catch(Exception){}
}
public void createTempDirectory(){
try{
saveLocation = "c:\\temp\\";
bool dirExists = System.IO.Directory.Exists(saveLocation);
if(!dirExists)
System.IO.Directory.CreateDirectory(saveLocation);
}
catch(Exception){}
}
public void createFilename(){
try{
var timeStamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
filename = TestContext.CurrentContext.Test.FullName;
string ext = ".png";
filename = filename + timeStamp;
filename = saveLocation + filename + ext;
}
catch(Exception){}
}
}
}
Reference:
ITakesScreenshot
Defines the interface used to take screen shot images of the screen.
GetScreenshot
Gets a Screenshot object representing the image of the page on the screen.
TestContext (NUnit)
The TestContext class allows tests to access certain information about the execution context.