2016-09-16 33 views
5

我在Microsoft測試管理器中有一個測試套件。每個測試都映射到特定的WorkItem ID。我想將所有具有相同工作項ID的測試作爲播放列表一起運行。以下是樣品測試的例子。在Microsoft測試資源管理器中創建具有相同工作項ID的測試方法的播放列表

[TestMethod] 
     [TestCategory("Cat A")] 
     [Priority(1)] 
     [WorkItem(5555)] 
     public void SampleTest() 
     { 
      Do some thing 
     } 

我試過了,但無法通過Workitem ID創建播放列表。請建議是否可以這樣做。

+0

爲什麼你不希望其他類別添加到測試?例如。 '[TestCategory(「Cat A」)] [TestCategory(「WorkItem 5555」)] public void SampleTest ...' – Gabrielius

回答

2

您將不得不使用反射。
獲取你的類的類型,獲取它的方法,然後搜索那些具有正確屬性的類。

MethodInfo[] methods = yourClassInstance.GetType() 
    .GetMethods()).Where(m => 
    { 
     var attr = m.GetCustomAttributes(typeof(WorkItem), false); 
     return attr.Length > 0 && ((WorkItem)attr[0]).Value == 5555; 
    }) 
    .ToArray(); 

請注意,如果您願意,您可以檢查多個屬性。
然後,您只需要使用父類的實例作爲啓動這些方法的目標。

foreach (var method in methods) 
{ 
    method.Invoke(yourClassInstance, null); 
} 

如果你的方法有參數,用含參數的object[]更換null

這裏是一個完整的工作示例,您可以嘗試:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 

namespace ConsoleApplication7 
{ 
    public class MyAttribute : Attribute 
    { 
     public MyAttribute(int val) 
     { 
      Value = val; 
     } 

     public int Value { get; set; } 
    } 

    class Test 
    { 
     [MyAttribute(1)] 
     public void Method1() 
     { 
      Console.WriteLine("1!"); 
     } 
     [MyAttribute(2)] 
     public void Method2() 
     { 
      Console.WriteLine("2!"); 
     } 
     [MyAttribute(3)] 
     public void Method3() 
     { 
      Console.WriteLine("3!"); 
     } 
     [MyAttribute(1)] 
     public void Method4() 
     { 
      Console.WriteLine("4!"); 
     } 
    } 

    class Program 
    { 

     static void Main(string[] args) 
     { 
      var test = new Test(); 

      var types = Assembly.GetAssembly(test.GetType()).GetTypes(); 

      MethodInfo[] methods = test.GetType().GetMethods() 
       .Where(m => 
        { 
         var attr = m.GetCustomAttributes(typeof(MyAttribute), false); 
         return attr.Length > 0 && ((MyAttribute)attr[0]).Value == 1; 
        }) 
       .ToArray(); 

      foreach (var method in methods) 
      { 
       method.Invoke(test, null); 
      } 
     } 
    } 
} 
相關問題