Code Coverage in VS 2012
Code Coverage is a option given for developers to make sure that the tests which they have written covers the code to be tested.
Visual Studio code coverage comes with VS 2012 Test Explorer. It supports both managed & unmanaged Code. Interesting thing is as Test Explorer supports 3rd party unit testing frameworks code coverage also can be used as well. So you can use the Unit test you wish & use Code Converge toll in VS 2012 inbuilt.
1. How to use
once you have run the tests you can right click on the tests in the Test Explorer & click on the on the option “Analyze Code Coverage for Selected Tests”
This will show you the code coverage result as below. This result gives you the option to navigate to the code as well. It will show code coverage percentages in following levels
- Total Code Coverage
- Assembly Level
- Class Level
- Method Level
Once you clicked on any level the text editor in VS will highlight & show you which are the code blocks which have not been covered by the tests written as follows.
2. What you prefer Block or Line?
Code Coverage can be counted using Blocks or Lines as you prefer.
- Block :- A block is a piece of code with exactly one entry and exit point. This will be shown as default in the Code Coverage Results.
- Lines :- If you prefer to see the Code Coverage by Lines then you can right click on the results & can select ‘Add or remove Column Option’. Then you’ll get tge following window where you can select the columns you want to see in the result set.
3. Excluding Elements for Results
If you need to exclude any class, struct, method, property, property setter or getter, event to be exclude from being counted for the code Coverage result VS 2012 gives you that facility as well. All you have to do is following.
1. Add following using statement inside your code.
using System.Diagnostics.CodeAnalysis;1. Add following attribute to the compenet you want to exclude.using System.Diagnostics.CodeAnalysis;public class CodeCoverageSample{ [ExcludeFromCodeCoverage] void ExampleMethod() {...}// exclude Method [ExcludeFromCodeCoverage] // exclude property string ExampleProperty1 { get {...} set{...}} int ExampleProperty2 { get { ... } [ExcludeFromCodeCoverage] // exclude setter set { ... } } } [ExcludeFromCodeCoverage] class ExampleClass2 { ... }//exclude class
note:- Excluding a class will not exclude is derived classes from the result set.
To get more details on code coverage customizing you can visit
http://msdn.microsoft.com/en-us/library/jj159530.aspx
4. Using Command Line
To run tests from the command line, use vstest.console.exe. Code coverage is an option of this utility. Open the Visual Studio Developer Command Prompt:
On the Windows Start menu, choose All Programs, Microsoft Visual Studio, Visual Studio Tools, Developer Command Prompt.
Run:
vstest.console.exe MyTestAssembly.dll /EnableCodeCoverage
Happy Coding !
Comments
Post a Comment