Member-only story
Code Coverage in .NET Core Projects

If you have created a unit test project in .NET Core, then you must have noticed a NuGet package, coverlet.collector
, is installed in the default project templates for MSTest and xUnit. What does this NuGet package do?
The coverlet
documentation (link) tells us that coverlet is a cross platform code coverage framework for .NET, with support for line, branch and method coverage. It means that we are able to check the code coverage for .NET Core applications using coverlet
. Very cool. 👏 👏 👏
In this blog post, we will go over the process of generating code coverage reports and uploading them to coveralls.io
. This whole process will be done using GitHub Actions.
The full project is in this GitHub repository. The tricks are in setting up the unit testing project and in writing scripts for coverage report generation and publishing. You should be able to follow along even if you are using another version control system or a different CI/CD provider.
In this project, I have created a .NET Core 3 class library and an MSTest project which references the class library. You might want to have a similar setup before we dive in.
Creating the Coverage Report
- Install the NuGet package
coverlet.msbuild
to the MSTest project using the following command.dotnet add package coverlet.msbuild
The pre-installed NuGet packagecoverlet.collector
doesn’t work with thedotnet test
command. Thus, we need to install thecoverlet.msbuild
package in order to generate coverage reports in the CI pipeline. This NuGet package integratescoverlet
with the .NET build system, so thatcoverlet
will compute code coverage after tests. - Run
dotnet test
command to generate a coverage report.
dotnet test /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=lcov
Several parameters are passed into the dotnet test
command. The first one, CollectCoverage=true
, means we want to collect code coverage.
The second parameter, CoverletOutput
, specifies the output file destination, which is in the TestResults
folder. The most commonly available .gitignore
file for .NET projects sets the TestResults
folder to be ignored for version control…