Wednesday, March 21, 2012

Testing Difficult Code

I recently did 3 videos in my ‘Using ApprovalTests in .Net’ series that deal with how to test difficult code. These video actually have very little to do with either .Net or ApprovalTests, but they are common issues you run into when unit testing.


Testing difficult Code comes down to 2 things:

  1. Can I call the Method?
  2. Will the Method run to completion?

And there are 2 techniques I use to deal with these, that individually are useful, but together are amazing.

1. The Peel

The hardest part about long methods is you have to run all of it to test even a small part of it. The idea behind the peel is to break the method up into easy to run pieces.  Here’s the video:

The Peel

2. The Slice (Mocks)

Even if you get into the piece you are looking to test, you might not be able to get all the way through it. That’s where mocks come into place. By slicing off the connection to the actual trouble spot, you can easily fake it, and return to easy to run code.

The Slice

3. The Peel & Slice

So now that you have these Mocks, how do you get them to be used? While there are many forms of dependency injection (inheritance, factory, DI frameworks, IoC) the easiest of all is “Parameter passing”. Of course, to do that you need a nice seam that passes in the default dependency. Sound familiar? This is why the Peel & Slice work so nicely together.

The Peel & The Slice

No comments: