2010-06-01 53 views
1

我最近将.NET 3.5的C#项目升级到.NET 4.我有一个方法从给定的MethodBase实例列表中提取所有MSTest测试方法。它的机身看起来是这样的:.NET中的自定义属性更改4

return null == methods || methods.Count() == 0 
    ? null 
    : from method in methods 
     let testAttribute = Attribute.GetCustomAttribute(method, 
      typeof(TestMethodAttribute)) 
     where null != testAttribute 
     select method; 

这个工作在.NET 3.5,但因为我的升级项目.NET 4中,这个代码总是返回一个空列表,即使给出的方法包含一个方法列表标记为[TestMethod]。 .NET 4中的自定义属性有所改变吗?

调试,我发现GetCustomAttributesData()上的测试方法,结果给出了两个CustomAttributeData一个列表,它是在Visual Studio 2010中的“当地人”窗口描述:

  1. Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItemAttribute("myDLL.dll")
  2. Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute() - 这就是我正在寻找

当我打电话GetType()对第二CustomAttributeData实例,但是,我得到{Name = "CustomAttributeData" FullName = "System.Reflection.CustomAttributeData"} System.Type {System.RuntimeType}。如何从CustomAttributeData中获得TestMethodAttribute,以便我可以从MethodBase列表中提取测试方法?

回答

2

对我而言愚蠢的错误:我的测试方法,提取方法是在参考Microsoft.VisualStudio.QualityTools.UnitTestFramework,以便它可以寻找一个类库项目TestMethodAttribute作为自定义属性。当我将我的解决方案从VS 2008升级到VS 2010时,转换过程会自动更新来自Microsoft.VisualStudio.QualityTools.UnitTestFramework的版本,版本= 9.0.0.0到Microsoft.VisualStudio.QualityTools.UnitTestFramework,版本= 10.0.0.0在我的测试项目中。但是,它没有更新我的类库项目中的引用,所以仍旧指向旧的UnitTestFramework引用。当我改变了项目指向10.0.0.0库,我的代码如下预期一样:

return null == methods || methods.Count() == 0 
    ? null 
    : from method in methods 
     let testAttribute = Attribute.GetCustomAttribute(method, 
      typeof(TestMethodAttribute)) 
     where null != testAttribute 
     select method; 

此外,代码Jon suggested工作为好,一旦我更新了参考。

2

您是否尝试过使用

method.GetCustomAttributes(typeof(TestMethodAttribute), false) 

呢?为自定义属性询问目标通常是我提取它们的方式。

这里是一个草率的例子:

using System; 
using System.Linq; 

[AttributeUsage(AttributeTargets.All)] 
public class FooAttribute : Attribute {} 

class Test 
{ 
    static void Main() 
    { 
     var query = typeof(Test).GetMethods() 
      .Where(method => method.GetCustomAttributes(
           typeof(FooAttribute), false).Length != 0); 

     foreach (var method in query) 
     { 
      Console.WriteLine(method); 
     } 
    } 

    [Foo] 
    public static void MethodWithAttribute1() {} 

    [Foo] 
    public static void MethodWithAttribute2() {} 

    public static void MethodWithoutAttribute() {} 

} 
+0

是的,我试过传递'true',所以它也检查祖先。我总是找回一个空的“对象”数组。 – 2010-06-01 17:51:12

+0

@Sarah:在这种情况下,请发布一个简短但完整的程序来展示问题。我已经展示了一个* does *工作的例子。 – 2010-06-01 17:52:09

+0

虚惊一场!我的项目引用了旧版.NET 3.5/VS 2008版本的UnitTestFramework库。切换到.NET 4/VS 2010版本的UnitTestFramework(10.0.0.0)解决了这个问题。 – 2010-06-01 18:08:56