Code Coverage and Unit Tests in VS2012

This article is about a question that people often ask when writing Unit tests and the dificulties a developer encounters; the question is:

When should I stop writing Unit Tests of something (for example, a simple function)?

Let's talk about something known as the Code Coverage feature in Visual Studio (Premium/Ultimate editions). Most people don't even know how it can help identify unused code. Code coverage actually does the instrumentation of the assembly with special symbols placed over each statement and then analyzes if that is being called when the code was executed. In Visual Studio this feature is added to the Test Manager. So you can run your unit tests via the coverage tool and analyze the report to determine how much production code is being covered by your unit tests.

The following is the simple procedure for runing the tests with coverage.

  1. In Visual Studio 2012 (Premium/Ultimate) you'll find the option "Test" –> "Analyze code coverage". Now there's an option to run a single test coverage or all tests coverage.


    Note: This option will be enabled only when your solution has UnitTests available. For unit tests written with Nunit you will need a Nuget package for Nunit Test Adapter. If you want that then you can also download the Nunit Visual Studio Extension by searching into the Visual Studio Extension online.
  2. Now select the Run All Tests option and the magic will start. The coverage tool will be automatically launched and will run all Unit tests.
  3. Once all the unit tests have run you'll see a coverage report in the Code Coverage results window that will provide you coverage in %.


In the Covered column of this report you'll see the percentage of every function. And if this report says 100% then stop writing the unit tests.


Stop Writing Unit tests at the moment

Though as a standard testing strategy you can stop when coverage is > 95%.