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.
May 8th, 2003 at 8:12 pm
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?
March 9th, 2004 at 6:32 pm
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.