Code coverage in .NET 5 (C#)
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
- ReporGenerator installation by command line:
> dotnet tool install --global dotnet-reportgenerator-globaltool
Build solution and run unit tests.
- Build the solution (Note: The command is runned from the repository root folder).
>dotnet build NetCoreCoverage.sln --configuration Release
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/"
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
Finally, see the results! 😎
In the path ‘.\TestResults\html\index.html’, you can find the output of the reporter command. And.. wuolah!
You can click in the different files (text in red color) and see the lines covered.
Extra post 🤓
- 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
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'])