Customers who sign-up prior to 30/06/2024 get unlimited access to free features, newer features (with some restrictions), but for free for at least 1 year.Sign up now! https://webveta.alightservices.com/
Categories
.Net UnitTests

Code coverage in .Net

This blog post can be considered obsolete. OpenCover tool has been archived. Refer to this blog post for latest:

Code coverage in .Net

This blog post covers code coverage in .Net. Particularly we would be discussing about code coverage using NUnit, OpenCover, ReportGenerator tools.

For the sake of this discusson we would assume we have some projects in the following namespaces:

Project1.Facade;

Project1.App

Project1.Service

Project1.Facade.Tests – NUnit Test Project

Project1.Service.Tests – NUnit Test Project

First we would need to run the tests using NUnit console test runner. The NUnit Console Test Runner can be downloaded from here under releases section. The assumption is the package has been installed under C:\ drive and C:\NUnit\nunit-console\nunit3-console.exe exists, if not adjust the path as necessary.

Create a batch file and call it “RunTests.bat” with the following content:

C:\NUnit\nunit-console\nunit3-console.exe .\Project1.Facade.Tests\bin\Debug\net6.0\Project1.Facade.Tests.dll
C:\NUnit\nunit-console\nunit3-console.exe .\Project1.Service.Tests\bin\Debug\net6.0\Project1.Service.Tests.dll

Now we will create another batch file “CodeCoverage.bat” for the commands for OpenCover and ReportGenerator. The assumption is that OpenCover and ReportGenerator have been installed at the following locations:

C:\OpenCover\OpenCover.Console.exe, C:\ReportGenerator\net6.0\ReportGenerator.exe.

The content of batch file would be:

C:\OpenCover\OpenCover.Console.exe -target:.\RunTests.bat -register:user -filter:"+[Project1*]* -[Project1*Tests]*" -oldstyle -mergeOutput

C:\ReportGenerator\net6.0\ReportGenerator.exe -reports:results.xml -targetdir:coverage

start .\coverage\index.htm

We first have OpenCover run the RunTests.bat it collects some data and generates results.xml file. The important parameters are the -filter, -oldstyle, -mergeOutput. The results.xml file becomes the input of ReportGenerator. ReportGeerator generates some reports and saves inside a directory by the name of coverage.

The last command opens the index.html file from the generated report.

A bunch of log files, xml files are generated during these. Assuming there are no other xml or log files, these can be removed easily by adding appropriate del commands in the second batch file.

The project structure is slightly different, but some sample Add and Subtract example screenshots can be seen below:

Hoping this post helps someone in improving coding practices! Worked a little bit late into the night, I work for myself – for my own startup, no worries!

Code coverage in .Net