Execute code on test failure

296 views Asked by At

I have a bunch of automated UI tests with Selenium and MSTest.

When a test fails I need to take a screenshot of the headless browser so I can diagnose what went on.

Currently I do this with a try catch throw but it needs repeating in every test.

[TestMethod]
public void TestThings()
{
    try
    {
        // do things
        Assert.Fail();
    }
    catch (Exception ex)
    {
        Driver.TakeScreenshot();
        throw;
    }
}

Repeating boilerplate code makes me sad, there must be a better way. Is there some onFailed thing I can hook into to do this kind of thing?

1

There are 1 answers

4
Mike Zboray On BEST ANSWER

Probably the easiest thing to do is use a TestCleanup and check the test outcome there:

// This will be set by the test framework.
public TestContext TestContext { get; set; }

[TestCleanup]
public void AfterTest()
{
    if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed) 
    {
        Driver.TakeScreenshot();
    }
}

You can put this in a base class and inherit all your test classes from it so you don't have to copy it into each class, as well.