A while ago, I wrote a blog post outlining a strategy using NUnit to test that methods raise exceptions when expected. At the time, I was surprised to discover that there seemed to be no good way to test this without resorting to a never ending list of try-catch blocks embedded within test fixtures. I wrote a method called AssertException to help in that regard and while it worked, AssertException used reflection and required you to pass parameters to methods being tested in a somewhat unnatural, type unsafe way.

I recently came across something in the NUnit framework that solved this problem nicely called Assert.Throws Using Assert.Throws is really easy. Pass it the type of exception you expect to be raised together with a code snippet that will raise the exception and it will test that the exception is actually raised. For example:

MyObject o = new MyObject();
Assert.Throws(typeof(ArgumentNullException), delegate() { o.MyMethod(null) }, "Argument null exception expected");

I'm not sure when Assert.Throws was added to the NUnit unit-testing framework, but it seems like a really useful addition that will really clean up many of our unit tests.