NUnit - Is it possible to check in the TearDown whether the test succeeded?

This has been already solved in Ran's answer to similar SO question. Quoting Ran:

Since version 2.5.7, NUnit allows Teardown to detect if last test failed. A new TestContext class allows tests to access information about themselves including the TestStauts.

For more details, please refer to http://nunit.org/?p=releaseNotes&r=2.5.7

[TearDown]
public void TearDown()
{
    if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
    {
        PerformCleanUpFromTest();
    }
}

sounds like a dangerous idea unless it's an integration test, with say data to remove say. Why not do it in the test itself?

Obviously a private flag in the class could be set.

This is what Charlie Poole himself has suggested if you must


If you want to use TearDown to detect status of last test with NUnit 3.5 it should be:

[TearDown]
 public void TearDown()
 {
   if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
   {
      //your code
   }
 }

Tags:

C#

.Net

Nunit