【问题标题】:Exclude class or method from code coverage in .net-core从 .net-core 中的代码覆盖范围中排除类或方法
【发布时间】:2016-10-06 23:31:34
【问题描述】:

我知道我能够使用 [ExcludeFromCodeCoverage] 排除 .Net 框架 4 中的代码覆盖率。

有谁知道我是否可以从 .dotnet 核心中排除代码覆盖率?

【问题讨论】:

标签: .net-core


【解决方案1】:

从 .NET Core 2.0 开始,您可以使用 ExcludeFromCodeCoverage 属性。

using System.Diagnostics.CodeAnalysis;

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

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

【讨论】:

  • 不幸的是,这对我来说不适用于 Asp.net core 2.2 web api 项目。我想排除从 dbcontext 搭建的 OnModelCreating() 方法。但它不起作用。运行代码指标,仍然显示可维护性指数非常低的方法。我希望该方法根本不显示,因为它是自动生成的。
【解决方案2】:

我终于找到了解决办法!

首先你需要使用 .runsettings 文件来配置代码覆盖率:

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

但问题是 ExcludeFromCodeCoverageAttribute 是密封的,所以我们不能使用它

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

我在这里发布了问题,看起来它将在下一个版本中解决

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

现在 我使用 .runsettings 示例中提到的 GeneratedCodeAttribute。 您还可以使用您的自定义属性或任何其他排除规则,如下所示:

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

【讨论】:

    【解决方案3】:

    创建您自己的 ExcludeFromCodeCoverage 属性

    [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; }
    }
    

    然后将其添加到您的 .runsettings 文件中并排除它。

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

    在分析代码覆盖率时不要忘记选择你的运行设置文件。

    More on customizing run settings

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多