Unit Testing: Code Coverage
Posted
Sun, Oct 25 2009 16:27
by
Deborah Kurata
Visual Studio 2008 (Team System ONLY) provides a really nice set of tools for viewing the code coverage of your unit tests.
NOTE: While Visual Studio 2008 Professional Edition has tools for building, executing, and debugging unit tests, it does NOT include the code coverage tools.
[To begin with an overview of unit testing, start here.]
Code coverage illustrates how much of the code was executed (or covered) by the unit tests.
NOTE: This post assumes you have already generated or created at least one unit test.
To view the code coverage for your unit tests:
1) Enable code coverage in the test run configuration file.
When you create your first unit test, Visual Studio adds a LocalTestRun.testrunconfig file to your solution under the Solution Items folder. Double-click on this file to open it:
Select Code Coverage from the left list:
Select the files on the right that you wish to view code coverage. Don't pick your test projects; rather pick the projects containing the code that is being tested. Then click Apply and Close.
2) Run your unit tests. The Test Results dialog appears.
See this prior post for more information on executing unit tests.
Your results should appear similar to the following:

3) If the tests pass, click the Show Code Coverage Results button in the far upper right corner of the Test Results dialog. The Code Coverage Results dialog appears.
This dialog displays all of the code in all of the files you selected for code coverage instrumentation. Drill down as needed to find the desired code.
In this case, the unit test is testing the getter and setter for the LastName. Notice that the covered percentage for both the getter and setter is 100%. That means that the unit test is executing every line of code in the getter and setter.
4) Double click on any item in the Code Coverage dialog to open the associated code window.
Notice how the code is color-coded. Blue shows code that was executed by the unit test. Red shows code that was not executed.
Use this feature to ensure you have unit tests for each unit of your code.
Enjoy!
EDITED 10/27/09: While Visual Studio 2008 Professional Edition has tools for building, executing, and debugging unit tests, it does NOT include the code coverage tools. In the original version of this post, I incorrectly stated that code coverage tools were available in the Professional Edition. This post has been corrected.