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

£可爱£侵袭症+ 提交于 2019-12-30 01:37:10

问题


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?


回答1:


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



回答2:


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



回答3:


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




回答4:


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



回答5:


    [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");

        }
    }



回答6:


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.



来源:https://stackoverflow.com/questions/1473201/nunit-is-it-possible-to-check-in-the-teardown-whether-the-test-succeeded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!