Tutorial :In the teardown event during an NUnit test how can I get to the attribute applied to the method that was just tested?



Question:

I have a test method that is run. When the method generates an exception I want to know what the name of the test was and the exception content.

In the teardown for the test I want to get access to this information. How would I get access to it from the [TearDown] attributed method?


Solution:1

OPTION 1: I don't think you can. Or rather, I don't know that you can. How I approach this need is to use a try/catch on the specific tests, do what I want with the exception and then throw again within the catch block so that the test could fail.

try{      // do something that can potentially throw;  }  catch(Exception ex){      // do something interesting with the ex;      throw;  }  

OPTION 2: If you've not gone too far along, you may want to use xUnit which has a different exception expectation model and may provide some of the control you are looking for.


Solution:2

I don't think there's a good way built in to nunit, but it's not a hard problem to resolve. Just wrap your tests in a try/catch block, catch any exceptions, and save them (and the test name) to a private member variable in your test class. Then you've got access from your TearDown method.

Not particularly elegant, but it works.


Solution:3

Another solution would be to use a template method and run all tests using this method. For example:

// template method  void Execute(Action test)  {      try      {          test();      }      catch (Exception e)      {          // handle exception here          throw;      }  }    [Test]  public void Test()  {      Execute(() =>          {              // your test here          });  }  

This pattern is particularly useful when your test uses some resources that must be initialized before test and disposed after test (e.g. temporary file). In that case, you can use a type parameter in test delegate.

Another advantage is that you can easily let the test run on different thread, using different culture etc.

Disadvantage is clear: it forces you to use lambda method in every test.


Solution:4

You can access text context objects in test tear down method

[TearDown]  public void TestTearDown()  {    // inc. class name    var fullNameOfTheMethod = NUnit.Framework.TestContext.CurrentContext.Test.FullName;     // method name only    var methodName = NUnit.Framework.TestContext.CurrentContext.Test.Name;    // the state of the test execution    var state = NUnit.Framework.TestContext.CurrentContext.Result.State; // TestState enum  }  

I don't which version was first to support it, but mine is 24.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »