tags:

views:

134

answers:

3

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  A: 

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

dove
Thats upsetting, I would have expected some sort of NUnit.CurrentTestContext API. I just need to know if the test succeeded as there is additional info that I can provide in this fixture if it failed that would help in debugging.
George Mauer
+1  A: 

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
}
}
Thomas Maierhofer
Its not an attempt to tell which test was run, just a different error that I would like to throw so i can get a more accurate stacktrace
George Mauer
A: 

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.

AdamRalph
As a rule, absolutely that is what you should do. However I like to keep my tests clean and cohesive with a BDD flavor. Sometimes that means setting up givens and asserts via lambdas and executing them in the TearDown. The problem is if for some reason the setup or test body failed the stacktrace is confusing.
George Mauer