【问题标题】:Skip testmethods in custom fxcop rule跳过自定义 fxcop 规则中的测试方法
【发布时间】:2014-07-24 23:22:42
【问题描述】:

我正在编写一个自定义 fxcop 规则来检查未使用的本地人。 (是的,有一个existing,但我想排除 TestMethods 被检查。)

Introspector 显示 TestMethodAttribute 在编译时可用:

我似乎无法真正检查属性是否存在。

我尝试了以下方法:

方法一。

_TestAttribType = FrameworkAssemblies.Mscorlib.GetType(Identifier.For("Microsoft.VisualStudio.TestTools.UnitTesting"), Identifier.For("TestMethodAttribute"));
AttributeNode testAttribute = method.GetAttribute(_TestAttribType);
if (testAttribute != null)
    return null;

方法二。

if(method.Attributes.Any(attrib => attrib.ToString().Contains("Test")))
    return null;

方法三。

if(method.Attributes.Any(attrib => attrib.Type == typeof(TestMethodAttribute))
    return null;

方法 1 不起作用,因为 Microsoft.VisualStudio.TestTools.Unittesting 不在 mscorlib 中。第二种方法也不起作用,我不知道为什么。第三种方法无法编译,因为 FxCop-API 不支持 TestMethodAttribute。

如何在我的 FxCop 规则中排除测试方法?

【问题讨论】:

  • 您希望对验证属性的确切类型有多严格?您是否只想忽略 MSTest TestAttribute,或任何名为“TestAttribute”的属性,或任何以“Test”开头或包含“Test”的属性?
  • 如果可能的话,我真的很想知道这两种方式,如果两者都可能的话。我接近解决方案了吗?
  • 引用核心框架程序集之外的类型并非易事,因此如果您可以接受这种方法,请使用名称。

标签: c# code-analysis fxcop


【解决方案1】:

仅基于名称的简单方法是:

method.Attributes.Any(a => a.Type.Name.Name == "TestMethodAttribute")

如果您想要一个更完整的解决方案并增强一些性能,请查看反编译器中MarkMembersAsStatic 规则中IsVSUnitTestMethod 方法的实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多