Thursday, 20 November 2014

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.

1 comment:

Nanang said...

There's also the fluent format:
Assert.That(() => sut.DodgyMethod(), Throws.InstanceOf<NullReferenceException>());

Or its inverse:
Assert.That(() => sut.DodgyMethod(), Throws.Nothing);

Unfortunately, if you want to capture the exception and do further assertions with it, you do need to use the Assert.Throws<>() syntax.
var ex = Assert.Throws<MyException>(() => sut.DodgyMethod());
Assert.That(ex.Message.Contains("dodgy"));