MSDN Community

.NET Development | Testing & Quality Assurance

Understanding and Implementing Code Coverage in .NET

Code coverage is a metric that describes the degree to which the source code of a program is executed during the execution of automated tests. A high code coverage percentage generally indicates a lower risk of undiscovered bugs. In .NET, several tools and techniques can help you measure and improve your code coverage.

Why is Code Coverage Important?

Tools for Code Coverage in .NET

Microsoft provides built-in support for code coverage, primarily through Visual Studio Enterprise and the .NET CLI.

1. Visual Studio Enterprise

Visual Studio Enterprise offers an integrated code coverage experience:

To use it:

  1. Ensure you have Visual Studio Enterprise installed.
  2. Open your test project or solution.
  3. Navigate to Test > Analyze Code Coverage > All Tests (or select specific tests).
  4. Run your tests. The coverage results will appear in a new pane.

2. .NET CLI (Coverlet, AltCover)

For developers using .NET Core/5+ and not exclusively Visual Studio Enterprise, or for CI/CD pipelines, command-line tools are essential.

Coverlet

Coverlet is a cross-platform code coverage framework for .NET.

Coverlet is a popular choice due to its ease of use and cross-platform compatibility.

Installation via NuGet Package Manager:

dotnet add package coverlet.collector --include-prerelease

Running tests with coverage:

dotnet test --logger trx --filter fullyQualifiedName!~IntegrationTests --collect:"XPlat Code Coverage"

This command executes tests and generates coverage reports (e.g., in LCOV, Cobertura formats).

AltCover

AltCover is another robust code coverage tool for .NET.

Installation:

dotnet tool install --global altcover

Running tests with coverage:

altcover build --include=ProjectToCover --coverlet --test-assembly path/to/your/test.dll

Best Practices for Code Coverage

Interpreting Coverage Reports

Coverage reports typically show metrics at different levels:

Pay close attention to uncovered lines and branches, especially in critical parts of your application.