Add code coverage to .Net Core 2.x or higher

Add code coverage to .Net Core 2.x or higher

When developing applications the complexity can skyrocket in only a few months time. Pieces of code that worked in the past suddenly throw errors or create unexpected results. One way to mitigate such issues is to write unit tests. This helps you maintain your code stability while taking away that nervous feeling when deploying to production.

Even after diligently writing your unit tests you will find code that's not tested properly. We are only humans and code evolves constantly letting faults creep in to our codebase. So how do we measure the amount of code tested and prevent this false feeling of security? The answer is simple, just check the amount of code that was tested by your unit tests, this is called code coverage. There are many different tools that you can add to your build pipelines but for simplicity we will use a nuget package named Coverlet to check our code coverage before checking in our code.

Compatibility

Coverlet.msbuild is compatible with MSTest and XUnit out of the box. In addition to showing a basic coverage percentage, it will output a JSON in the root of the unit test project. This document describes what is covered and what not, from here it’s possible to use a report generator for more visualization possibilities.

(Piece of) Cake

It is definitely possible to integrate Coverlet with Cake and Visual Studio Code. There is already tooling available for real-time code coverage information. If you are interested I can recommend this blog post from Scott Hanselman.

Instructions for .Net Core >= 2.0.0

Add the coverlet.msbuild package to your project containing the unit tests by using the nuget package manager or by typing following command in the package manager console Install-Package coverlet.msbuild and selecting the correct default project

code-coverage-001.png

After installing the package you can run the command dotnet test /p:CollectCoverage=true in the terminal of your choice

code-coverage-002.png

Now you're ready to take your codebase to the next level just don't forget to invest in qualitive unit testing as well as quantity.