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:
1
dotnet test --collect:"XPlat Code Coverage"
Finally, you can use reportgenerator command to generate a report with actual coverage in your code:
1
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:
1
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.