Code coverage report generation for dotnet core applications

In "Working Effectively with Legacy Code" Michael Feathers introduced a definition of legacy code as code without tests, since a code without tests is difficult to maintain, extend and evolve. It doesn't matter if you are using the latest technologies, if you don't test your code, it will hard to change without breaking anything, which will make it rigid and difficult to maintain. Remember that unit tests are the base in the testing pyramid.

In order to ensure that you are covering with unit tests the most important part of our application, code coverage can be helpful to detect where you have lack of tests.

Code coverage is a tool offered by products like ReSharper or the Enterprise version of Visual Studio. However, these products are not free and you might not want to pay for this essential feature.

But if you are working with dotnet core, it is quite easy to get a code coverage report thanks to ReportGenerator package.

In order to generate your tests, first you need to install ReportGenerator in your machine with this command:

dotnet tool install -g dotnet-reportgenerator-globaltool

Then you can run your tests and create coverage reports by using this command:

dotnet test --collect:"XPlat Code Coverage"
Finally, you can use reportgenerator command to generate a report with actual coverage in your code:
reportgenerator "-reports:./**/coverage.cobertura.xml" "-targetdir:./coverage" "-reporttypes:Html"
And that is all. Handy, right?. In addition, since I like to make it even more easy to execute, I've created a .bat file, which execute my tests, generates a coverage report, and opens chrome to display the report. As a result, I can update my coverage report with double-click. This is the code for my script:
dotnet test --collect:"XPlat Code Coverage"
reportgenerator "-reports:./**/coverage.cobertura.xml" "-targetdir:./coverage" "-reporttypes:Html"
start chrome ./coverage/index.html
In order to provide an example, I've created this GitHub project with some tests: https://github.com/albertocorrales/code-coverage-report
 
When I execute my coverage.bat script, my browser is automatically opened displaying this coverage report.
 

In our report we can see the coverage for each of our files and different metrics like line coverage, branch coverage, etc.
 
I hope you found helpful this article.
 
 

Comments

Popular posts from this blog

Building Micro-Frontends with Single-Spa

AWS assuming role + MFA with pulumi (and other applications)

Managing snapshots for Amazon ElasticSearch with Dotnet Core Lambdas