I recently upgraded a C# project from .NET 3.5 to .NET 4. I have a method that extracts all MSTest test methods from a given list of MethodBase
instances. Its body looks like this:
return null == methods || methods.Count() == 0
? null
: from method in methods
let testAttribute = Attribute.GetCustomAttribute(method,
typeof(TestMethodAttribute))
where null != testAttribute
select method;
This worked in .NET 3.5, but since upgrading my projects to .NET 4, this code always returns an empty list, even when given a list of methods containing a method that is marked with [TestMethod]
. Did something change with custom attributes in .NET 4?
Debugging, I found that the results of GetCustomAttributesData()
on the test method gives a list of two CustomAttributeData
which are described in Visual Studio 2010's 'Locals' window as:
Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute("myDLL.dll")
Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()
-- this is what I'm looking for
When I call GetType()
on that second CustomAttributeData
instance, however, I get {Name = "CustomAttributeData" FullName = "System.Reflection.CustomAttributeData"} System.Type {System.RuntimeType}
. How can I get TestMethodAttribute
out of the CustomAttributeData
, so that I can extract test methods from a list of MethodBase
s?