5

How can I exclude a method from code coverage reporting using coverlet and reportgenerator. Excluding entire namespaces in .runsettings works as expected but using [ExcludeFromCodeCoverage] attribute excludes the entire file instead of only the targeted method. See Comments below for what I've tried in .runsettings.

relevant .runsettings lines:

  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector>
        <Configuration>
          <Format>lcov</Format>
          <Include>[*]*</Include>
          <Exclude> 
             <!-- excluded namespaces -->
          </Exclude>
          <!-- excludes entire file from coverage --> 
          <ExcludeByAttribute>Obsolete, GeneratedCodeAttribute, CompilerGeneratedAttribute,ExcludeFromCodeCoverage</ExcludeByAttribute>
          <!-- included & reported as uncovered --> 
          <ExcludeByAttribute> ExcludeFromCodeCoverageAttribute </ExcludeByAttribute>
          <SingleHit>true</SingleHit>
          <UseSourceLink>true</UseSourceLink>
          <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
          <!-- included and reported as uncovered -->
          <CodeCoverage>
            <Attributes>
              <Exclude>
                <Attribute> ^System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute$</Attribute>
              </Exclude>
            </Attributes>
          </CodeCoverage>
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>

UPDATE: It seems to have been a recently resolved issue with coverlet. Updating resolved the issue. https://github.com/coverlet-coverage/coverlet/issues/809

Don
  • 3,876
  • 10
  • 47
  • 76

1 Answers1

8

Just apply [ExcludeFromCodeCoverage] on the method instead of the class.

  • i need exclude test project assembly ?how to do this – Karthic G Mar 23 '21 at 08:35
  • @KarthicG I don't recommend you to do that, but... if you really want - you should pass `/p:IncludeTestAssembly=false` parameter to your `dotnet test` command. – Yevheniy Tymchishin Mar 23 '21 at 21:27
  • Can you elaborate why _you_ don't recommend to do that? There must be a reason for that recommendation I assume. – 321X Mar 24 '21 at 13:51
  • @321X sure, in that case you will not get a quick observation that all tests in your test assembly are executed. https://github.com/coverlet-coverage/coverlet/pull/318#issuecomment-457223596 – Yevheniy Tymchishin Mar 24 '21 at 21:52