简体   繁体   中英

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

I would like to have my TearDown method check whether the previous test was a success before it applies some logic. Is there an easy way to do this?

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();
    }
}

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
   }
 }

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

Only if you do this manually. In fact you even won't know which tests are intend to run. In NUnit IDE one can enable some tests and disable some other. If you want to know if some specific test has run you could include code like this in your test class:

enum TestStateEnum { DISABLED, FAILED, SUCCEDED };
TestStateEnum test1State = TestStateEnum.DISABLED;

[Test]
void Test1()
{
test1State =  TestStateEnum.FAILED; // On the beginning of your test
...
test1State =  TestStateEnum.SUCCEDED; // On the End of your Test
}

Then you can check the test1State variable. If the test throws an exception it won't set the SUCCEDED. you can also put this in a try catch finally block in your tests with a slightly different logic:

[Test]
void Test1()
{
test1State =  TestStateEnum.SUCCEDED; // On the beginning of your test
try
{
    ... // Your Test
}
catch( Exception )
{
   test1State =  TestStateEnum.FAILED;
   throw; // Rethrows the Exception
}
}
    [OneTimeTearDown]
    public void AfterEachTest()
    {
        if (TestContext.CurrentContext.Result.Outcome.Status.Equals(TestStatus.Failed))
        {
           Console.WriteLine("FAILS");

        }
        else if (TestContext.CurrentContext.Result.Outcome.Equals(ResultState.Success))
        {
            Console.WriteLine("SUCESS");

        }
    }

IMHO tear down logic should be independent of test results.

Ideally you should avoid using setup and teardown completely, a al xunit.net. See here for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM