Test Coverage Tools in VS2008

Perhaps I spend a bit too much time “working” and not enough time learning the ins and outs of my tools. I stumbled across the Code Coverage Results tab this morning and was quite pleased.

The Code Coverage metrics count what lines of code are not tested in your project. I’ve seen 3rd party tools that so this, but never found this inside of Visual Studio. To use these tools, I believe you must use the Visual Studio testing framework (which I do).

Here’s how to get it working.

1. Enable Code Coverage in the local test run configuration for your test project.

Test > Edit Test Run Configurations > Your Test Configuration

Click on Code Coverage and check the libraries to include in the code coverage routines.

2. Execute your Test Project. After the tests are complete, right-click one of the tests and select “Code Coverage Results”.

3. Use the Code Coverage Results window to analyze the coverage of your unit tests.

In the image above, you can see that ERC.Models has VERY poor coverage. That’s a LINQ library that, quite honestly, DOES have poor coverage as all of the code is automatically generated. The implementation of the Model (in ERC.Controllers) has quite good coverage, but has room for improvement.

I can further drill down into the ERC.Controllers namespace and see that I left out the ReportsController. I remember creating the tests for the controller, but I added a quick method to it and forgot to update the test.

For this controller, with only a few lines, it’s easy to spot the problem but what about a namespace or class with thousands of lines of code? This is where the code highlighting comes in handy.

4. Use Code Highlighting to pick out the missed lines of code. Click on the Code Highlighting button to toggle highlighting on and off.

The code highlighting button, seen to the left, toggles red highlights on and off in your code. This only works for code that is included in your code coverage metrics, but helps the developer find those little code blocks that may have been overlooked.

In my ReportsController, I remember adding a quick method, but forgetting to update the test. I can open up that controller and see that the untested code is now highlighted.

From here, I can go back, add or update the approprate tests, and rerun.

It’s a simple feature, but GREAT to see it built in—especially now that I know it’s there! The only caveat is that I wish you could (or wish I knew how to) exclude pre-generated code, such as LINQ code.