New features in NUnit 2.5. Part 2 – testing exceptions

June 25, 2009 Waldemar Mękal

In part 1 I have presented how to use parameterized test methods in NUnit 2.5. In this post I want to show a new way of testing exceptions by NUnit.

Previously, we could use ExpectedException attribute. It looked like the one below.

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExceptionTest()
{
    ...

    someObject.MethodThatThrowsException(null);
}

That approach had several drawbacks – only one exception could be tested in a single method, there was no way to test exception message or any exception property. The new way is to use Assert.Throws method. It takes exception type and TestDelegate, in which code that throws exception should be placed, as arguments. Below, two overloads are presented – the first one with type argument, the second – with typeof operator.

[Test]
public void ExceptionTest()
{
    ...

    Assert.Throws<ArgumentNullException>(
        () => someObject.MethodThatThrowsException(null));

    Assert.Throws( typeof(ArgumentNullException),
        delegate { someObject.MethodThatThrowsException(null) } );
}

Assert.Throws returns an exception that is expected. It gives us an opportunity to check some properties of thrown exception.

[Test]
public void ExceptionTest()
{
    ...

    ArgumentException ex = Assert.Throws<ArgumentException>(
        () => someObject.MethodThatThrowsException(""));
    Assert.That(ex.Message, Is.EqualTo("Arg not given!"));
}

There is also an overload of Assert.Throws which uses constraints.

[Test]
public void TestException()
{
    Assert.Throws( Is.TypeOf<ArgumentException>(),
        () => someObject.MethodThatThrowsException(null) );
}

That’s all. You can find more information in nunit documentation.

Last posts