Coverlet - exclusion of code coverage study by attribute

In this note, I will show how to exclude specific classes from the code coverage and add the appropriate configuration to Nuke.

Exclusion by attribute (ExcludeByAttribute)

When I was looking for 100% code coverage with unit tests, I faced the problem of how to exclude automatically generated code. Unfortunately, this information was terribly hard for me to find, so I am sharing it here.

As the documentation shows, each attribute intended for exclusion must be passed separately:

--exclude-by-attribute 'Obsolete' --exclude-by-attribute'GeneratedCode' --exclude-by-attribute 'CompilerGenerated'

More holistic example:

coverlet /path/to/test-assembly.dll --target "dotnet" --targetargs "test /path/to/test-project --no-build" --exclude-by-attribute 'Obsolete' --exclude-by-attribute'GeneratedCode'


To add an exclusion to Nuke, you need to modify the parameters of the code coverage. Taking a piece of code from the second part about Nuke, one line would need to be added:

CoverletSettings PrepareCoverageSettingsForCoveringProject(Project project, CoverletSettings settings,
    DotNetTestSettings coverageTestSettings, ref string previousCoverageFileResult)
    var assemblyPath = FindAssemblyForProject(project);
    var coverageResultDirectory = TestResultDirectory / project.Name;

    settings = settings
        .SetProcessArgumentConfigurator(_ => _.Add(@"--exclude-by-attribute CompilerGeneratedAttribute --exclude-by-attribute GeneratedCodeAttribute")) (1)
        .SetOutput(coverageResultDirectory + "/")

    settings = MergeCoverageResultsWithPreviousRun(previousCoverageFileResult, settings);
    previousCoverageFileResult = SetThresholdForLastRun(project, coverageResultDirectory, ref settings);

    return settings;
1 This one line is enough to exclude code marked with CompilerGeneratedAttribute and GeneratedCodeAttribute attributes.
comments powered by Disqus
Please keep in mind that the blog is in preview form at this point and may contain many errors (but not merit errors!). Nevertheless, I hope you enjoy the blog! Many illustrations appeared on the blog thanks to!
Built with Hugo
Theme Stack designed by Jimmy