11

I know i was able to use [ExcludeFromCodeCoverage] to exclude code coverage in .Net framework 4.

Does anyone know if there's a way i can exclude code coverage from .dotnet core?

Andrey Stukalin
  • 5,328
  • 2
  • 31
  • 50
kepung
  • 2,102
  • 2
  • 22
  • 24

3 Answers3

8

Since .NET Core 2.0 you can use ExcludeFromCodeCoverage attribute.

using System.Diagnostics.CodeAnalysis;

namespace YourNamespace
{
    [ExcludeFromCodeCoverage]
    public class YourClass
    {
        ...
    }
}

https://isscroberto.com/2019/07/11/net-core-exclude-from-coverage/

Roberto Orozco
  • 579
  • 7
  • 11
  • 1
    Unfortunately this, does not work for me for an Asp.net core 2.2 web api project. I wanted to exclude the OnModelCreating() method that was scaffolded from the dbcontext. But it does not work. Running the code metrics, still shows the method with a very low maintainability index. I would like for that method to not show at all, since it is auto-generated. – SoftDev30_15 Sep 20 '19 at 11:42
3

I finally found solution!

First of all you need to use .runsettings file to configure code coverage:

https://msdn.microsoft.com/en-us/library/jj159530.aspx

BUT the problem is that ExcludeFromCodeCoverageAttribute is sealed so we can't use it

https://github.com/dotnet/corefx/blob/93b277c12c129347b5d05de973fe00323ac37fbc/src/System.Diagnostics.Tools/src/System/Diagnostics/CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs

I posted question here and looks like it will be solved in next release

https://github.com/dotnet/corefx/issues/14488

FOR NOW I use GeneratedCodeAttribute as mentioned in .runsettings example. You can also use your custom attribute or any other exclude rule like here:

https://msdn.microsoft.com/en-us/library/jj159530.aspx

Vladimir Rodchenko
  • 1,052
  • 15
  • 25
0

Create your own ExcludeFromCodeCoverage attribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Interface)]
public class ExcludeFromCodeCoverageAttribute : Attribute
{
    public ExcludeFromCodeCoverageAttribute(string reason = null)
    {
        Reason = Reason;
    }

    public string Reason { get; set; }
}

Then add it to your .runsettings file and exclude it.

...
   <Configuration>
      <CodeCoverage>
        .
        .
        .
        <Attributes>
          <Exclude>
            <Attribute>^YourCompany\.YourNameSpace\.sExcludeFromCodeCoverageAttribute$</Attribute>
          </Exclude>
        </Attributes>
        .
        .
        .
    </Configuration>
...

Don't forget to select your run setting file when analyzing the code coverage.

More on customizing run settings

Aboo
  • 2,314
  • 1
  • 18
  • 23