Search code examples
nunitspecflow

Hook in NUnit or SpecFlow when a test fails


So I am using SpecFlow with NUnit for developing end-to-end acceptance tests of a web application with Selenium. One of the things we do to try to gauge the nature of a failure, is to take a screenshot of the browser whenever a regression test fails. I am currently doing it by wrapping each of my tests in try/catch blocks, and taking the screenshot in the catch with Selenium then, rethrowing the exception. This works, but it makes the tests messier and more tedious.

Is there a way in either NUnit or SpecFlow to call a hook when any test fails, before any teardown method is called?


Solution

  • You can use the ScenarioContext to detect if a scenario generated an error.

    ScenarioContext.Current.TestError
    

    If not null, then an error occurred. You can check this and use it to determine whether to take a screenshot or not. You can see an example on SpecFlow's documentation reference.

    You can also make this an AfterScenario Hook so you do not need to have the try/catches everywhere. It would simply check every test at the end to see if an error occurred and whether to create a screenshot.