BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Testing
.NET 1.1+

NUnit Exception Assertions

The tenth part of the Automated Unit Testing tutorial continues looking at the NUnit framework's assertions. This article describes the assert methods that are used to test that the correct exceptions are thrown by the code under test.

Using Lambda Expressions

If you are using .NET 3.5, you can replace the delegate or anonymous method with a parameterless lambda expression, making the code even simpler. The example below is identical to the previous two tests but uses a lambda:

[Test]
public void PassingANullTaxRateCausesAnException()
{
    Assert.Throws(typeof(ArgumentNullException),
        () => { _calculator.AddTax(_orderValue, null); });
}

Using Type Parameters

As with other NUnit assertions that accept a type as a parameter, when using .NET 2.0 or later you can replace the parameter with the type parameter of a generic method. The example below shows this as a fourth way to represent the same test:

[Test]
public void PassingANullTaxRateCausesAnException()
{
    Assert.Throws<ArgumentNullException>(() => { _calculator.AddTax(_orderValue, null); });
}

Assert.DoesNotThrow

Sometimes you will want to test that a call does not throw an exception. In these situations you can use Assert.DoesNotThrow. This assertion does not include an argument for the type of exception. It tests that no exception of any type is thrown.

[Test]
public void PassingAValidTaxRateCausesNoException()
{
    Assert.DoesNotThrow(() => { _calculator.AddTax(_orderValue, null); });
}

Assert.Catch

When you write software that throws exceptions, you may later refactor your code and change the type of exception that used. Usually this means using a more specialised exception that is derived from the one previously used. One problem with Assert.Throws is that it checks for a specific exception type, ignoring inheritance hierarchies. We can demonstrate this using the TaxCalculator class. If the class was initially designed to throw an ArgumentException, the test may have been as follows:

public void PassingANullVATRateCausesAnArgumentException()
{
    Assert.Throws(typeof(ArgumentException),
        () => { _calculator.AddTax(_orderValue, null); });
}

The above test fails because we are checking for an ArgumentException and the AddTax method throws an ArgumentNullException. Instead of using Assert.Throws, we can use Assert.Catch. This provides similar functionality but passes if the caught exception type is derived from that specified. Therefore, the following test passes.

public void PassingANullVATRateCausesAnArgumentException()
{
    Assert.Catch(typeof(ArgumentException),
        () => { _calculator.AddTax(_orderValue, null); });
}
22 April 2011