简体   繁体   English

在自定义fxcop规则中跳过测试方法

[英]Skip testmethods in custom fxcop rule

I am writing a custom fxcop rule which checks for Unused locals. 我正在编写一个自定义fxcop规则来检查未使用的本地人。 (Yes, there is an existing one, but I want to exclude TestMethods from being checked.) (是的,有一个现有的,但我想从被检查排除TestMethods。)

Where Introspector shows me that the TestMethodAttribute is available at compiletime: Introspector向我展示TestMethodAttribute在编译时可用: 在此输入图像描述

I can not seem to be able to actually check if the Attribute exists. 我似乎无法真正检查属性是否存在。

I tried the following methods: 我尝试了以下方法:

Method 1. 方法1。

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

Method 2. 方法2。

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

Method 3. 方法3。

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

Method 1 would not work because Microsoft.VisualStudio.TestTools.Unittesting is not in mscorlib. 方法1不起作用,因为Microsoft.VisualStudio.TestTools.Unittesting不在mscorlib中。 The second method didn't work either, I am not sure why. 第二种方法也不起作用,我不知道为什么。 Third method does not compile, because TestMethodAttribute is not supported by the FxCop-API. 第三种方法无法编译,因为FxCop-API不支持TestMethodAttribute。

How can I exclude testmethods from being checked in my FxCop-rule? 如何排除在我的FxCop规则中检查测试方法?

A simple approach based on the name only would be: 基于名称的简单方法是:

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

If you want a more complete solution with some performance enhancements, take a look at the implementation of the IsVSUnitTestMethod method in the MarkMembersAsStatic rule in a decompiler. 如果您想要一个具有一些性能增强功能的更完整的解决方案,请查看反编译器中MarkMembersAsStatic规则中IsVSUnitTestMethod方法的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM