Code coverage in .NET 5 (C#)

Javier Carracedo
3 min readMay 9, 2021

--

A simple example of how to get coverage metrics in a .NET 5 solution.

How to get C# code coverage in a .NET 5 solution?

In this post, I will use the dotnet command, Coverlet and ReportGenerator to build a .NET 5 solution, run unit tests and get coverage metrics in this formats (HTML principaly, or CSV).

You can find the code used in this post in the following GitHub Repository:

jke94 / NetCoreCoverage 💻

Let´s go! 😀

Tools installation

  1. ReporGenerator installation by command line:
> dotnet tool install --global dotnet-reportgenerator-globaltool
Command line output

Build solution and run unit tests.

  1. Build the solution (Note: The command is runned from the repository root folder).
>dotnet build NetCoreCoverage.sln --configuration Release
Commad line output

2. Run unit tests the solution (Note: The command is runned from the repository root folder) and generate results. This command will displayed in the command line the results of the coverage, and futhermore, this command will generate an ooutput file (.\TestResults\coverage.cobertura.xml)

>dotnet test NetCoreCoverage.sln --configuration Release /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:Exclude="[xunit*]\*" /p:CoverletOutput="../TestResults/"
Commad line output

3. Generate report coverage metrics in html format. This command consume the ‘.\TestResults\coverage.cobertura.xml’ file and generate a output folder with a index.hmtl file to visualize the results in a browser.

>reportgenerator "-reports:TestResults\coverage.cobertura.xml" "-targetdir:TestResults\html" -reporttypes:Html 
Commad line output

Finally, see the results! 😎

In the path ‘.\TestResults\html\index.html’, you can find the output of the reporter command. And.. wuolah!

Index.html file

You can click in the different files (text in red color) and see the lines covered.

Doctor.cs class coverage

Extra post 🤓

  1. Coverage output in CSV file in state of HTML output.

Could be util to import data in a Microsoft Excel sheet for example o Microsoft Power BI

>reportgenerator "-reports:TestResults\coverage.cobertura.xml" "-targetdir:TestResults\csv" -reporttypes:CsvSummary
Summart.csv file with the metrics

2. Implement with Jenkins software in a jenkins pipeline and publish the results, for example with the plugin HTML Publisher.

Here, a example step in jenkins using HTML Publisher plugin:

publishHTML (target : [allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'reports',
reportFiles: 'myreport.html',
reportName: 'My Reports',
reportTitles: 'The Report'])

--

--

Javier Carracedo
Javier Carracedo

Written by Javier Carracedo

Hi! SW Engineer from León (Spain) . I ❤ my work, I like improve and to grow my knowledge about different technologies. SW Engineer at HP SCDS - León (Spain)

No responses yet