NUnit ExpectException Attribute is an AntiPattern

Consider the following test:

[Test]
[ExpectException(ExceptionType)]
public void ExceptionThrownByVerifier() {
doSomeSetup();
doSomeProcessing();
callSomethingThatThrowsTheException();
}

This is intended to test that callSomethingThatThrowsTheException() throws an excption. And lets say it passes.

The test is right - yeah? Wrong

If doSomesetup() throws an Exception then this is testing nothing - I’ll never know - and the test won’t tell me that it is useless.

The correct way to do this test is uglier, but actually works:

[Test]
public void ExceptionThrownByVerifier() {
doSomeSetup();
doSomeProcessing();
try {
callSomethingThatThrowsTheException();
fail("Expected Exception");
}
catch (ExceptionType e) {
//expected
}
}

If doSomeSetup() throws an Exception, then the test will fail, and tell me why.

2 Responses to “NUnit ExpectException Attribute is an AntiPattern”

  1. Luke Says:

    Isn’t ExpectException intended to look for a particular Exception type, though? Wouldn’t it still be a failure if a different type of exception was thrown?

  2. Tim Says:

    NUnit also has support for TestSetupAttribute and TestFixtureSetupAttribute, with matching TearDown attributes too. These can be used in many cases to separate code like doSomeSetup(); from the test case itself.
    I’m still new to NUnit and at first glance ExpectedExceptionAttribute looks like unnecessary syntactic sugar, but I don’t think it qualifies as an AntiPattern.

Leave a Reply