TFS 2012 Build Code Coverage – Filtering unwanted assemblies / test assemblies.

Code coverage with TFS Build can be enabled by editing the build definition and modifying the Automated Tests settings. Unfortunately this may instrument more assemblies than you want it to. For example, Unit Test projects will appear as part of the code coverage results.

To solve this there is a filter mechanism that determines which assemblies will be instrumented; however it can be non obvious to configure.

The trick is to include a .runsettings file within your solution that contains rules on the assemblies to include/exclude. It is a xml structure and full details of the schema can be found here.  (Do not confuse with .testsettings).    You can also install a Visual Studio Template to automatically add the basic .runsettings file directly from Add New Item.

Then edit the xml to exclude or include specific assemblies (or alternatively use regex to match paths). For instance, If you want to exclude all assemblies where its name finishes ‘Tests.dll’  then you can add the following to the Exclude section:

1  <ModulePaths\>                      <Exclude\>                 <ModulePath\>.\*Tests.dll</ModulePath\>         </Exclude\>  </ModulePaths\>

Note: that this matches on full path names so you need to bear this in mind when forming your regex

Check the .runsettings file into TFS.

Now edit the build definition, –>Process,  –> Automated Test,   ….and instead of selecting ‘Enable Code Analysis’; select ‘Custom’ and provide the source control path to the .runsettings file.

image

This is it.
Save the build definition and start a new build. It should run Tests and Code Analysis and use the .runsettings file to determine which assemblies to instrument.

Note: One gotcha to watch out for is that the Options drop down shows different choices depending on where you attempt to configure it. If you use the Automated Tests Dialog then the option is ‘Custom’ as above. If you edit without opening the dialog then the choice is UserSpecified. Go figure

image