For one of the projects, we needed a branch level code coverage report to be generated. Visual Studio 2012 supports code coverage with different unit testing frameworks. But Visual Studio is not producing the branch level code coverage details.
We are using the NUnit as unit testing framework for the project. So we analysed the different code coverage tools available for .Net projects. We found the OpenCover with ReportGenerator is the best option available with complete NUnit features (the NCover yet to support the TestCaseSource Attribute).
But it lacks IDE integration. So I found a way to generate and invoke the reports from Visual Studio toolbar.
- Basically the script first invokes the NUnit unit testing tool. Command line console reference : http://www.nunit.org/index.php?p=consoleCommandLine&r=2.2.5
- OpenCover captures the NUnit testing results and produces the coverage report in .XML format. Usage reference : https://github.com/OpenCover/opencover/wiki/Usage
- ReportGenerator produces the HTML report based upon OpenCover’s Results.XML. Usage Reference : https://reportgenerator.codeplex.com/
- Invoke the html summary report created in coverage sub-folder
- Install the necessary nuget packages
PM> install-package Nunit.Runners
PM> install-package OpenCover
PM> install-package ReportGenerator
Create simple batch file to be invoked from Visual Studio.
- Create following .bat file in unit test project with the name Coverage.bat.
- Change the “Copy to Output Directory” property to “Copy always” value. This will copy the file to bin folder or unit test project.
Note: In this batch file replace OpenCover.4.5.2506, ReportGenerator.220.127.116.11 with the versions deployed in your project
REM @echo suppresses command line. ^ is line continuation character
REM $(BinDir) is VS command line parameter of bin folder path of the selected project
-targetargs:”<ASSEMBLY>.UnitTest.dll /noshadow /nologo” ^
-filter:”+[<ASSEMBLY>*]* -[<ASSEMBLY>.DataModel]* -[<ASSEMBLY>.UnitTest]* -[<ASSEMBLY>.Diagrams]*” ^
REM Default filters are: -[mscorlib]* -[mscorlib.*]* -[System]* -[System.*]* -[Microsoft.VisualBasic]*
REM delete old coverage files
REM /F /Q switches to delete files and directories even with readonly attribute without confirmation
DEL /F /Q .\coverage\*.*
REM Generate HTML based coverage reports
-reports:results.xml -targetdir:coverage Verbosity: Error
REM invoke the html coverage summary in browser
- Create the External Tool entries in Visual Studio and in toolbar
Configure the “External Tools” to Coverage.Bat in bin folder as shown in below screenshot. This will execute the commands within the IDE and will display the output in Visual Studio’s “Output” window.
If you configured this as first External Tool this will be displayed as “External Command 7″ (by default visual studio has 6 external tools preconfigured). You can add this menu item to necessary toolbar (I configured to Build tool bar) as shown in below steps.