Testing for Exceptions with NUnit

I’ve been aware for a long time usual way of writing a unit test with NUnit that expects an Exception to be thrown is to use the ExpectedExceptionAttribute on the test method.

[ExpectedException(typeof(ArgumentException)]
[Test]
public void Test()
{
    var sut = new ThrowUp();

    sut.DodgyMethod(3);
}

I hadn’t noticed that around the release of NUnit 2.5, an alternative was added. The Assert.Throws method allows you to be specific about which bit of code in the test should be throwing an exception.

public void Test()
{
    var sut = new ThrowUp();

    Assert.Throws<ArgumentException>( () => sut.DodgyMethod(3) );
}

I think it’s a good improvement, and makes it a bit clearer where the exception should be coming from.

Written on November 20, 2014