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:
- Double-click the "[Local].testsettings" file in the Solutions Items folder in the Solution Explorer window.
- In the "Test Settings" dialog, choose the "Data and Diagnostics" item.
- In the list of roles, select "Code Coverage" and immediately click the '"Configure" button.
- In the "Code Coverage Detail" dialog select the assemblies to instrument for Code Coverage.
- Run your test scenario and in the "Test Tools" toolbar, click the icon "Code Coverage Results".
- 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:
- Compile the solution and copy the DLLs and PDBs from the Debug folder to the new folder
- Instrument DLLs in the Visual Studio Command Prompt using Vsinstr.exe -coverage <.dll >
- Sign the instrumented DLLs using the command Sn.exe -R < dll > <file_name.snk>
- 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
- Enter the following text to stop capturing: vsperfcmd –shutdown
- It will not stop until the processes are restarted, so restart ISS (iisrest in admin cmd)
Requirements
- Visual Studio Ultimate, Visual Studio Premium
Unit Tests
To analyze Code Coverage on unit tests in Test Explorer:
- On the Test menu, choose Analyze Code Coverage.
- 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.
- 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.