Azure DevOps makes it very easy to run unit tests and display code coverage results in your builds, but I noticed, by default, it was also showing test coverage of 3rd party DLLs, in my case, Moq. These DLLs are not being tested in my application, so it brings the code coverage percentage down. I’m going to show you how to add your own custom test run settings to your solution and builds so that you can ignore code coverage for DLLs that are not being tested in your application.

    1. Start by adding a .runsettings file to the root of your application solution. You can look at an example here, but for my purposes, I really only needed the exclude modules piece (highlighting the specific module exclusion I added below), so my finished run settings file looked like this:
      <?xml version="1.0" encoding="utf-8"?>
      <RunSettings>
      	<DataCollectionRunSettings>
      		<DataCollectors>
      			<DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      				<Configuration>
      					<CodeCoverage>
      						<ModulePaths>
      							<Exclude>
      								<ModulePath>.*CPPUnitTestFramework.*</ModulePath>
      								<ModulePath>.*moq.*</ModulePath>
      							</Exclude>
      						</ModulePaths>
      						<!-- We recommend you do not change the following values: -->
      						<UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
      						<AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
      						<CollectFromChildProcesses>True</CollectFromChildProcesses>
      						<CollectAspDotNet>False</CollectAspDotNet>
      					</CodeCoverage>
      				</Configuration>
      			</DataCollector>
      		</DataCollectors>
      	</DataCollectionRunSettings>
      </RunSettings>
      
    2. Now, we need to tell our test runner, to use this run settings file. I’m using the VSTest@2 YAML task, so for me, it looks like this:
      
      - task: VSTest@2
        inputs:
          platform: '$(buildPlatform)'
          configuration: '$(buildConfiguration)'
          runSettingsFile: 'YourRunSettingsNameFileName.runsettings'
          codeCoverageEnabled: true
          testSelector: 'testAssemblies'
          testAssemblyVer2: |
           **\*test*.dll
           !**\*TestAdapter.dll
           !**\obj\**
      
      
    3. Now, with any luck, run your build, and you should see that Azure DevOps is only showing you code coverage for DLLs you want to get coverage on!