Wednesday 5 January 2011

Basic unit test coverage reporting with PartCover

I’m fed up with having to guess at how much of my code is covered with unit tests and there’s no budget for NCover. So, after a bit of hunting I came across PartCover, an open source code coverage tool for .Net (https://github.com/sawilde/partcover.net4). As I’ve just started using it so I thought I’d jot down a few notes on the basics of getting a coverage report working.

The first step is creating a settings file. This is an XML file containing the settings PartCover will use to produce a coverage report.

<PartCoverSettings>
  <Target>C:\path_to_nunit\nunit-console-x86.exe</Target>
  <TargetWorkDir>C:\path_to_source\EnquirySubmissionServiceCoreTests\bin\Debug</TargetWorkDir>
  <TargetArgs>EnquirySubmissionServiceCoreTests.dll</TargetArgs>
  <Rule>+[*]*</Rule>
  <Rule>-[EnquirySubmissionServiceCore]EnquirySubmissionServiceCore.Some.Namespace*</Rule>
  <Rule>-[log4net*]*</Rule>
  <Rule>-[Moq*]*</Rule>
  <Rule>-[nunit*]*</Rule>
  <Rule>-[EnquirySubmissionServiceCoreTests*]*</Rule>
</PartCoverSettings>

You need to provide a path to NUnit, a working directory (the directory containing the assembly to check), the target assembly and a set of rules. The rules are basically RegEx and tell PartCover what to include and what to exclude from the report. My rules say include everything (+[*]*) then start excluding assemblies I don’t want in the report.

Note line 6 of the above settings file. It is possible to exclude specific namespaces within an assembly so you can exclude files you don’t want to be tested for coverage. In fact, you can even exclude specific classes in the same way.

I saved the settings file into the PartCover installation directory and then ran PartCover.exe:

partcover.exe --settings settings.xml --output output.xml

This runs the PartCover with the settings file and creates an XML file containing the output (in this case named output.xml). The output file can be opened with PartCover.Browser.exe to view the results:

untitled

That’s it for a basic setup and first report generation. Looks like I’ve got a few unit tests to write…