Tutorial Guide

Mastering index: coverlet.collector

The coverlet.collector package is the recommended way to collect code coverage in modern .NET. It uses the VSTest Data Collector infrastructure to provide a clean, out-of-process collection experience.

1. Installation

To get started, add the collector package to your unit test project (xUnit, NUnit, or MSTest):

dotnet add package coverlet.collector

2. Basic Usage

Once installed, you can collect coverage by passing the --collect parameter to the dotnet test command:

dotnet test --collect:"XPlat Code Coverage"

This will generate a Cobertura coverage.cobertura.xml file in a randomly named subfolder within the TestResults directory.

3. Advanced Configuration

For complex projects, you can use a .runsettings file to configure the collector behavior, such as output formats and exclusion filters.

<!-- runsettings example -->
<DataCollectionRunSettings>
  <DataCollectors>
    <DataCollector friendlyName="XPlat Code Coverage">
      <Configuration>
        <Format>json,cobertura</Format>
        <Exclude>[MyProject.Tests]*</Exclude>
      </Configuration>
    </DataCollector>
  </DataCollectors>
</DataCollectionRunSettings>
!
Ensure you specify the friendlyName exactly as "XPlat Code Coverage" for the collector to be recognized.

Why choose the Collector driver?

Unlike the MSBuild driver, the collector driver does not require modifying your build targets. This makes it safer for large enterprise solutions where build stability is paramount.