Computing code coverage for a .NET project

 
 
  • Gérald Barré

In an older post, I covered how to compute code coverage for a .NET Core project using Coverlet. The .NET SDK 8 now includes everything you need to compute code coverage without any additional dependencies. Microsoft also provides a .NET tool to process the coverage files.

Let's start by creating a new xUnit project and removing the dependency on coverlet.collector as we don't need it anymore:

PowerShell
dotnet new xunit
dotnet remove package coverlet.collector

You can then run the tests and compute the code coverage with the following commands:

PowerShell
dotnet test --results-directory "test-results" --collect:"Code Coverage"
dotnet test --results-directory "test-results" --collect:"Code Coverage;Format=cobertura"

The --collect:"Code Coverage" argument tells the test runner to collect code coverage data and save the coverage files in the test-results directory. These files use a VS-specific format (.coverage) that other tools cannot read. You can change the output format using "Code Coverage;Format=cobertura", or convert them to the Cobertura format using the dotnet-coverage tool (documentation):

PowerShell
dotnet tool update --global dotnet-coverage

Coverage reports are stored in folders with randomly generated GUIDs, making them difficult to locate and merge. Fortunately, dotnet-coverage supports globbing:

PowerShell
dotnet-coverage merge --output test-result.cobertura.xml --output-format cobertura "test-results/**/*.coverage"

You can then process the Cobertura file as needed. For example, you can publish it as an artifact in Azure DevOps or generate an HTML report with ReportGenerator:

PowerShell
dotnet tool install --global dotnet-reportgenerator-globaltool
reportgenerator -reports:test-result.cobertura.xml -targetdir:coverage-report -reporttypes:"Html_Dark"

If you use GitHub Actions, you can also publish the coverage summary as a Job Summary, so the coverage is easily accessible from the run:

YAML
on:
  push:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: dotnet test --results-directory "test-results" --collect:"Code Coverage"
      - run: dotnet tool update --global dotnet-coverage
      - run: dotnet-coverage merge --output test-result.cobertura.xml --output-format cobertura "test-results/**/*.coverage"
      - run: dotnet tool install --global dotnet-reportgenerator-globaltool
      - run: reportgenerator -reports:test-result.cobertura.xml -targetdir:coverage-report -reporttypes:"MarkdownSummaryGithub"
      - run: cat coverage-report/SummaryGithub.md >> $GITHUB_STEP_SUMMARY

Code coverage displayed as a job summary in GitHub Actions

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?