Take screenshot on test failure + exceptions Take screenshot on test failure + exceptions selenium selenium

Take screenshot on test failure + exceptions


If you put the screenshot logic in your TearDown method it will be called after each test finishes, no matter if it succeeded or failed.

I use a base class that has a function which wraps the tests and catches all exceptions. When a test fails the exception is caught and a screenshot is taken.

I use this base class for all my Selenium tests and it looks something like this:

public class PageTestBase{    protected IWebDriver Driver;    protected void UITest(Action action)    {        try        {            action();        }        catch (Exception ex)        {            var screenshot = Driver.TakeScreenshot();            var filePath = "<some appropriate file path goes here>";            screenshot.SaveAsFile(filePath, ImageFormat.Png);            // This would be a good place to log the exception message and            // save together with the screenshot            throw;        }    }}

The test classes then look like this:

[TestFixture]public class FooBarTests : PageTestBase{    // Make sure to initialize the driver in the constructor or SetUp method,    // depending on your preferences    [Test]    public void Some_test_name_goes_here()    {        UITest(() =>        {            // Do your test steps here, including asserts etc.            // Any exceptions will be caught by the base class            // and screenshots will be taken        });    }    [TearDown]    public void TearDown()    {        // Close and dispose the driver    }}


In C# I use NUnit 3.4. This offeres the OneTimeTearDown method that is able to access the TestContext including the state of the previous executed test. Do not use TearDown because it is not executed after a test fails ;)

using OpenQA.Selenium;using System.Drawing.Imaging;...[OneTimeTearDown]public void OneTimeTearDown(){    if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)    {        var screenshot = ((ITakesScreenshot)driver).GetScreenshot();        screenshot.SaveAsFile(@"C:\TEMP\Screenshot.jpg", ImageFormat.Jpeg);    }}


For greater justice here is the code for the MSTest

public TestContext TestContext { get; set; }[TestCleanup]public void TestCleanup(){  if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)  {    var screenshotPath = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss.fffff}.png";    MyDriverInstance.TakeScreenshot().SaveAsFile(screenshotPath);    TestContext.AddResultFile(screenshotPath);  }}