[ACCEPTED]-NUnit - Is it possible to check in the TearDown whether the test succeeded?-nunit
This has been already solved in Ran's answer to similar 6 SO question. Quoting Ran:
Since version 2.5.7, NUnit 5 allows Teardown to detect if last test failed. A 4 new TestContext class allows tests to access 3 information about themselves including the 2 TestStauts.
For more details, please refer 1 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 1 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 4 an integration test, with say data to remove 3 say. Why not do it in the test itself?
Obviously 2 a private flag in the class could be set.
This 1 is what Charlie Poole himself has suggested if you must
Only if you do this manually. In fact you 10 even won't know which tests are intend to 9 run. In NUnit IDE one can enable some tests 8 and disable some other. If you want to know 7 if some specific test has run you could 6 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 5 you can check the test1State variable. If 4 the test throws an exception it won't set 3 the SUCCEDED. you can also put this in a 2 try catch finally block in your tests with 1 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");
}
}
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.