In the past, I have written a blog post about code coverage using NUnit, OpenCover and ReportGenerator – https://www.alightservices.com/2022/06/23/code-coverage-in-net/.
OpenCover development has stopped for over 2 years.
This blog post talks about another tool known as Coverlet.
This blog posts has a accompanying Github repo – https://github.com/ALightTechnologyAndServicesLimited/CodeCoverage/
The code has 4 methods regarding DateTime class. And 3 helper methods:
- double GetUnixEpoch(DateTime)
- DateTime GetDateTimeFromUnixEpoch(double)
- long GetYYYMMDD(DateTime)
- bool IsLeapYear(int)
There are 9 unit tests for the above mentioned 4 methods.
The batch file – RunCodeCoverage.bat has the commands.
The usage is very simple, add the Coverlet nuget package, install the ReportGenerator tool and run some commands. Navigate to the unittest project.
dotnet add package coverlet.collector
dotnet tool install -g dotnet-reportgenerator-globaltool
The nuget package coverlet.collector needs to be added for every unit test project. The reportgenerator can be installed once.
Then run this command for invoking coverlet:
dotnet test --collect:"XPlat Code Coverage"
This generates a xml file under TestResults/[some-random-guid].
This xml file would be used by reportgenerator for generating HTML report:
reportgenerator.exe "-reports:TestResults**.*.xml" "-targetdir:report"
The above command looks for xml files under TestResults/* folder and generates HTML reports under report folder.
The HTML report looks like this. If there is any code that was not covered under unit test, those can be seen easily. The following screenshots have 100% code coverage, but if there is any code not covered, the code would be shown in red.
–
Mr. Kanti Kalyan Arumilli
B.Tech, M.B.A
Founder & CEO, Lead Full-Stack .Net developer
ALight Technology And Services Limited
Phone / SMS / WhatsApp on the following 3 numbers:
+91-789-362-6688, +1-480-347-6849, +44-07718-273-964
+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)
kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.