Code Coverage in Visual Studio

In my previous article I demonstrated how to do code analysis to remove dead code from a project. Removing dead/unreachable code will help to improve the Code Coverage percentage.

Code Coverage

To determine what portion of your project's code is actually being tested by coded tests such as unit tests, you can use the Code Coverage feature of Visual Studio. Using the Code Coverage feature we can determine how much code is being tested and we can reduce the number of bugs.

Set Up Code Coverage

The following is the procedure to set up Code Coverage in Visual Studio:

  1. Double-click the "[Local].testsettings" file in the Solutions Items folder in the Solution Explorer window.
  2. In the "Test Settings" dialog, choose the "Data and Diagnostics" item.
  3. In the list of roles, select "Code Coverage" and immediately click the '"Configure" button.
  4. In the "Code Coverage Detail" dialog select the assemblies to instrument for Code Coverage.
  5. Run your test scenario and in the "Test Tools" toolbar, click the icon "Code Coverage Results".
  6. Done.


Set Up Code Coverage using the Command line

The following is the procedure to set up Code Coverage in Visual Studio using the Command line:

  1. Compile the solution and copy the DLLs and PDBs from the Debug folder to the new folder
  2. Instrument DLLs in the Visual Studio Command Prompt using Vsinstr.exe -coverage <.dll >
  3. Sign the instrumented DLLs using the command Sn.exe -R < dll > <file_name.snk>
  4. Start capturing Code Coverage using the command “C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Performance Tools\x64\VSPerfCmd.exe /start:coverage /output:c:\test\Output.coverage /crosssession /user:everyone
  5. Enter the following text to stop capturing: vsperfcmd –shutdown
  6. It will not stop until the processes are restarted, so restart ISS (iisrest in admin cmd)


  • Visual Studio Ultimate, Visual Studio Premium

Unit Tests

To analyze Code Coverage on unit tests in Test Explorer:

  1. On the Test menu, choose Analyze Code Coverage.
  2. To see which lines have been run, choose Show Code Coverage Coloring Icon Show Code Coverage Coloring.

    To alter the colors, or to use bold face, choose "Tools", "Options", "Environment", "Fonts and Colors", "Show settings for: Text Editor". Then under "Display Items", adjust the Coverage items.
  3. If the results show low coverage then investigate which parts of the code are not being exercised, and create more tests to cover them. Development teams typically aim for about 80% Code Coverage. In some situations, lower coverage is acceptable. For example, lower coverage is acceptable where some code is generated from a standard template.


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now