tags:

views:

391

answers:

3

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?

A: 

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.

Pita.O
+2  A: 

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.

McWafflestix
A: 

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.

dkl