Friday, December 16, 2005 3:20 PM
by
joeybeninghove
Unit Testing Your Exceptions
Apparently the ExpectedException attribute doesn't work quite as well as it should in VS 2005 unit tests. As far as I know this should make a test fail:
<code>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), "expected message"))]
public void MethodThrowsArgumentNullExceptionWithValidMessage()
{
SomeClass context = new SomeClass();
context.SomeMethodThatThrowsArgumentNullException(); // throws ArgumentNullException with a message of "bad message"
}
</code>
Now, shouldn't that fail because the exception messages don't match? Well, it doesn't. So here's what I do as an alternative, albeit not exactly a satisfactory one.
<code>
[ExpectedException(typeof(ArgumentNullException)))]
public void MethodThrowsArgumentNullExceptionWithValidMessage()
{
string expected = "expected message";
try
{
SomeClass context = new SomeClass();
context.SomeMethodThatThrowsArgumentNullException(); // throws ArgumentNullException with a message of "bad message"
}
catch (ArgumentNullException ex)
{
string actual = ex.Message;
StringAssert.StartsWith(actual, expected);
throw;
}
}
</code>
This test will fail because the actual exception message doesn't start with your expected exception message.
This way you check both the exception type and exception message.