I am writing a custom fxcop rule which checks for Unused locals. (Yes, there is an existing one, but I want to exclude TestMethods from being checked.)
Where Introspector shows me that the TestMethodAttribute is available at compiletime:
I can not seem to be able to actually check if the Attribute exists.
I tried the following methods:
Method 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.
if(method.Attributes.Any(attrib => attrib.ToString().Contains("Test")))
return null;
Method 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. 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.
How can I exclude testmethods from being checked in my FxCop-rule?
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.