Performing Code Coverage for .NET Core 2.0 applications

As part of all my builds I provide code coverage. After executing the unit tests, I then perform code coverage over the source code. I won’t go into the reasons why this is necessary (I’ve written about code coverage in previous articles and almost certainly will again), but for me it’s a vital part of every build. Without code coverage you have no idea how effective your unit testingstrategy is.

I use a tool called dotcover to provide code coverage. This is a utility from JetBrains (the same people who create Resharper) and is a genuinely brilliant tool. It integrates into Visual Studio and can be run from the command-line as part of a script (which is exactly how I use it in our builds).

Unfortunately I couldn’t get it working with our ASP.NET Core 2.0 application. The documentation states that it should work with .NET Core but after many attempts I just couldn’t get it working. There is a command-line utility called dotnet that ships with .NET Core that can be used to perform all manner of functions, such as creating projects, testing projects, adding references to projects etc. I was already using dotnet to execute my unit tests, and thought that I’d try using it for my code coverage also.

As it happens there is an open-source utility that integrates directly with dotnet that performs code coverage. It’s called coverletand is available on Github here[^]. There are examples on using the utility here[^]

One issue that I came across was executing this from Team Foundation Services (TFS). Despite working without error from the command-line on the build server, I was getting an error when executing it as part of the build from TFS. I managed to eventually resolve this by explicitly specifying the name of the project and suppressing dotnet test from performing a build and restore.

Hide Copy Code

dotnet test "MyProject.Tests.csproj" --no-build --no-restore /p:CollectCoverage=true

This generates a JSON file containing the generated code coverage. Whilst this is not as pretty as the output from dotcover (which is simply exceptional) it at least works and gives me code coverage for our .NET Core 2.0 project.

Another problem encountered, another problem solved

Image for post
Image for post

A father, cyclist, vegetarian, atheist, geek and multiple award winning technical author. Loves real ale, fine wine and good music. All round decent chap.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store