Although my personal programming preference these days is towards BDD, I’ve spent the last few months teaching my new team traditional TDD because a) they’ve done a little bit of it before and b) we decided together that it’s a slightly easier entry point than BDD (I use a custom framwork for laying out my BDD so it’s a bit more involved).
So I’m back writing TDD and I’m a bit rusty but one thing that has bugged me in TDD for a while is the way NUnit provides built in support for catching exceptions – I’ve always found the ExpectedException attribute really hard to work with. Here’s a very simple example:
I don’t know about anybody else but I find this format very hard to follow and I’ve definitely had frustrations in the past with more complicated examples or when I’m trying to test more than one thing (i.e. Exception type, error message etc).
So I’ve recently been getting interested in some functional programming techniques and having done a bit of rudimentary reading I put together a helper class to handle these exception assertions as well as making them more readable/usable:
If you’re not used to functional programming this may look quite complicated at first glance but if you can imagine that the Action<T> parameter in the GetAssertionFailure method just represents an action that can be called on an object of type T (e.g. a method called FindLocation). And once you pass an object of the relevant type to the helper, it just invokes the method you’ve asked it to, catches the exception and then returns it wrapped up in a custom object.
Long story short it means that you can now write your exception test like this:
You can see the use of a lambda to represent the call to the FindLocation action with the invalid parameter and you can see how easy it is to access the returned exception and then implement separate asserts for each of the elements you want to check.
Feel free to shoot it down as it probably could be improved upon (I’ve been thinking about if I could infer the typeof(T) from the passed in parameter) but for now it makes our code cleaner & easier to read to so it’s been a good step forward.
Until next time…



March 23, 2010 at 11:49 pm |
NUnit provides a better way to handle exceptions than the ExpectedExceptionAttribute approach with the Throws method on the Assert class.
With this you can do Assert.Throws(() => locationService.FindLocation(“Invalid Postcode”));
The method returns the thrown exception so you can then make additional assertions as required.
March 24, 2010 at 4:56 pm |
nice work. I’m definitely stealing that!
March 25, 2010 at 9:47 am |
Thanks for the feedback Mike, I’ll have a look at that & see how it compares – could save us lots of time & energy!