• .NET
  • C#
  • XUnit
  • Code Coverage

Excluding Your .NET Test Project From Code Coverage

This article as a code snippet I use with my .NET test projects to be excluded them from code coverage metrics collection.


I have a large solution and an extension that will give me feedback on my code coverage, well by default it will also give you the metrics. Well I do not want this done on my test projects, since I don't test my tests.

Code Snippet

And here it is, in your csproj just add this Assembly Attribute, and now your project will not have its code coverage metric tallied.

<Project Sdk="Microsoft.NET.Sdk">
        <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />

Bonus: Code Snippet

And here is a Bonus Snippet! I use this to simplify and consolidate all the base settings for my Test Projects. Include the code below in a Directory.Build.props file at the root of your tests folder, where all your projects are located. The configuration includes the Assembly Attribute, from above, and all my common PackageReferences I like to use in my tests.

    <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />


        <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />

        <PackageReference Include="AutoFixture" Version="4.17.0" />
        <PackageReference Include="AutoFixture.AutoMoq" Version="4.17.0" />
        <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
        <PackageReference Include="FluentAssertions" Version="5.10.3" />
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.0" />
        <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
        <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="5.0.0" />
        <PackageReference Include="Xunit" Version="2.4.1" />
        <PackageReference Include="Xunit.Runner.Visualstudio" Version="2.4.3">
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        <PackageReference Include="coverlet.msbuild" Version="2.8.1" />
        <PackageReference Include="MediatR" Version="8.1.0" />
        <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.1.0" />
        <PackageReference Include="Moq" Version="4.15.2" />


Cody's logo image, it is an abstract of a black hole with a white Event Horizon.

Cody Merritt Anhorn

A Engineer with a passion for Platform Architecture and Tool Development.