In this post, I will note down steps to collect human-readable code coverage for .net core/standard apps on the developer machine.
I have created a simple .NET standard class library and .net core test project (xUnit) project here.
You will require the following NuGet packages to be installed on the xUnit tests project (BeingCraftsman.CoverageDemo.Tests).
- Microsoft.NET.Test.Sdk (Preinstalled as a part of xUnit tests project)
- xunit (Preinstalled as a part of xUnit tests project)
- xunit.runner.visualstudio (Preinstalled as a part of xUnit tests project)
Install it using the command:
dotnet add package coverlet.msbuild
Install it using the following two commands:
dotnet new tool-manifest
dotnet tool install dotnet-reportgenerator-globaltool
- Open Powershell and navigate to the tests project directory (In my case, BeingCraftsman.CoverageDemo.Tests).
- Check if the command
dotnet testis running all tests.
- Collect the coverage in a folder (./CodeCoverage in my case) and mention the format opencover.
ReportGenerator will generate a human-readable report but for that, it requires raw code coverage file in OpenCover format.
dotnet test /p:CollectCoverage=true /p:CoverletOutput="./CodeCoverage/" /p:CoverletOutputFormat="opencover"
- Convert opencover format to web pages (Human readable one).
dotnet reportgenerator "-reports:.\CodeCoverage/coverage.opencover.xml" "-targetdir:.\CodeCoverage\Web"
- Open generated report
Getting tired of running all these commands one by one.
Next time, onwards, just combine them with “;” separated and execute.
dotnet test /p:CollectCoverage=true /p:CoverletOutput="./CodeCoverage/" /p:CoverletOutputFormat="opencover"; dotnet reportgenerator "-reports:.\CodeCoverage/coverage.opencover.xml" "-targetdir:.\CodeCoverage\Web"; start .\CodeCoverage\Web\index.htm
Brief description of tools/commands:
dotnet test command is used to execute unit tests in a given solution. The
dotnet test command builds the solution and runs a test host application for each test project in the solution.
More details: https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test
Coverlet is Cross platform code coverage for .NET. How it works.
Coverlet also integrates with the build system to run code coverage after tests. In our case, MSBuild is the build system and hence we are using this package. For other build systems, you would require another package.
More details: https://github.com/coverlet-coverage/coverlet
ReportGenerator converts coverage reports generated by OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.
More details: https://github.com/danielpalme/ReportGenerator