I don’t suffer from classic OCD (Obsessive Compulsive Disorder), but I do sometimes have OCD tendencies. Just ask my poor wife when we’re having dinner while my mind is still trying to resolve a thorny programming problem. Earth to Phil. Are you on this planet?
Lately, the object of my OCD-like tendencies is getting the Subtext unit test code coverage up to 40%. At the time of this writing (and after much work), it is at 38%. Why 40%? No reason. Just a nice round number that we’ve never yet hit. Remember, OCD isn’t necessarily a rational affliction.
So here’s the anatomy of a code coverage addiction. First, I simply right click on our unit test project, UnitTests.Subtext, from within VisualStudio.NET 2005 (also works with older versions of VS.NET). I select the Test With menu option and click Coverage as in the screenshot below.
After running all of the unit tests, NCoverExplorer opens up with the a coverage report.
I can drill down to take a look at code coverage all the way down to the
method level. In this case, let’s take a look at the Subtext.Akismet
assembly. Expanding that node, I can drill down to the Subtext.Akismet
namespace, then to the
HttpClient class. Hey! The
only has 91% code coverage! I’ve gotta do something about that!
When I click on the method, NCoverExplorer shows me the code in the right pane along with which lines of code were covered. The lines in red were not executed by my unit test. Click on the below image for a detailed look.
As you can see, there are a couple of exception cases I need to test. It turns out that one of these exception cases never happens, which is why I cannot get that line covered. This may be better served using a Debug.Assert statement than throwing an exception.
If you haven’t played around with TestDriven.NET and NCoverExplorer, give it a twirl. But be careful, this is powerful stuff and you may spend the next several hours writing all sorts of code to get that last line of code tested.
Here are a few posts I’ve written that you may find useful to eke out every last line of code coverage.
- Unit Test Events With Anonymous Delegates
- Using Rhino Mocks to Unit Test Events On Interfaces
- Using WebServer.WebDev for Unit Tests
- A Testing Mail Server for Unit Testing Email Functionality
- Simulating Http Context For Unit Tests Without Using Cassini nor IIS
- Unit Testing Data Access Code with the StubDataReader
Now get out there and test!