Code Coverage made Easy: A Step-by-Step Guide for .NET 6

For .Net 4.8 it was enough to install Visual Studio Enterprise Edition on the build server and check the box for code coverage in the Testing task of Azure DevOps. The build agent then collected the coverage data and published it as part of your builds. Unfortunately, for .Net 6 this no longer works, and we need to go through a lot more steps.

There are a handful projects for code coverage that support .Net “core”, but not every project is still under active development. Be careful when you select a coverage tool and make sure that there is still some activity going on.

 

Coverlet

We settled for Coverlet because of its active development and the integration into dotnet test. We use the coverlet.collector package that we need to add to all test projects:

 

Generate code coverage files

Coverlet integrates nicely with dotnet test and all we need to do is to add the option --collect:"XPlat Code Coverage":

When we run this command, Coverlet will create a coverage.cobertura.xml file for each test project and put it into the folder TestResults.

 

Create a report with ReportGenerator

The different coverage files are a good start, but we want to have a combined report with the code coverage over the whole project. For that we use the project ReportGenerator.

We can install ReportGenerator as a global tool with this command:

After we installed ReportGenerator, we can run this command to turn our various coverage files into a single HTML report:

There are many additional options for ReportGenerator that you can explore on reportgenerator.io/usage. This site will also create the necessary command line parameters for your inputs or the YAML configuration for your build pipeline.

 

The code coverage report

If everything works, you get an HTML code coverage report like this one:

The HTML code coverage report shows you in which parts you need to add tests.

 

Exclude code from the coverage report

ReportGenerator offers us filters to include or exclude code at these levels:

  • Assemblies
  • Classes
  • Files

If we prefix the filter with a +, it will include it, while a will exclude it. To combine multiple filters, we can add a semicolon (;) between the filters.

 

Next

With everything in place to collect the code coverage of our tests on our local developer machine, we have reached a first important milestone. Next week we activate code coverage for our build pipelines in Azure DevOps and find a way around the annoying obstacles that come with this task.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.