codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Code Coverage in .NET Core Projects

Changhui Xu
codeburst
Published in
6 min readNov 22, 2019

--

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

  1. Install the NuGet package coverlet.msbuild to the MSTest project using the following command.
    dotnet add package coverlet.msbuild
    The pre-installed NuGet package coverlet.collector doesn’t work with the dotnet test command. Thus, we need to install the coverlet.msbuild package in order to generate coverage reports in the CI pipeline. This NuGet package integrates coverlet with the .NET build system, so that coverlet will compute code coverage after tests.
  2. 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…

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

No responses yet

Write a response