2012-05-23 25 views
6

我有一個包含測試用例的nunit類庫。我想以編程方式獲取庫中所有測試的列表,主要是測試名稱和測試ID。這是我到目前爲止:以編程方式獲取nunit庫中的測試列表,而無需運行測試

var runner = new NUnit.Core.RemoteTestRunner(); 
runner.Load(new NUnit.Core.TestPackage(Request.PhysicalApplicationPath + "bin\\SystemTest.dll")); 
var tests = new List<NUnit.Core.TestResult>(); 
foreach (NUnit.Core.TestResult result in runner.TestResult.Results) 
{ 
    tests.Add(result); 
} 

問題是,runner.TestResult爲空,直到您真正運行測試。我顯然不想在這一點上運行測試,我只想獲得庫中哪些測試的列表。之後,我會讓用戶選擇一個測試並單獨運行測試,並將測試ID傳遞給RemoteTestRunner實例。

那麼我怎樣才能得到測試列表,而沒有實際運行所有的測試?

回答

6

您可以使用反射來加載程序集並查找所有test屬性。這會給你所有的測試方法。其餘的由你決定。

下面是關於使用反射來獲取類型屬性的msdn示例。 http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

+1

+1,但是有一個奇怪的問題:與TestCaseAttribute可以參數化測試方法,從而變成多個(邏輯)的測試。沒有什麼不能通過反思來處理,但要牢記。 –

+0

@ Christian.K好處,OP要記住。 –

+0

我原本想這樣做,因爲它會給我測試(功能)名稱,但它不會給我測試ID。只要我可以做一個RemoteTestRunner運行過濾測試名稱而不是測試ID,那麼這應該工作正常,將檢查出來。 – Justin

4

這裏是檢索所有的測試名稱出測試類庫組件的代碼:

//load assembly. 
      var assembly = Assembly.LoadFile(Request.PhysicalApplicationPath + "bin\\SystemTest.dll"); 
      //get testfixture classes in assembly. 
      var testTypes = from t in assembly.GetTypes() 
       let attributes = t.GetCustomAttributes(typeof(NUnit.Framework.TestFixtureAttribute), true) 
       where attributes != null && attributes.Length > 0 
       orderby t.Name 
        select t; 
      foreach (var type in testTypes) 
      { 
       //get test method in class. 
       var testMethods = from m in type.GetMethods() 
            let attributes = m.GetCustomAttributes(typeof(NUnit.Framework.TestAttribute), true) 
        where attributes != null && attributes.Length > 0 
        orderby m.Name 
        select m; 
       foreach (var method in testMethods) 
       { 
        tests.Add(method.Name); 
       } 
      } 
1

由Justin答案不適合我的工作。下面做(用Test屬性檢索所有的方法名):

Assembly assembly = Assembly.LoadFrom("pathToDLL"); 
foreach (Type type in assembly.GetTypes()) 
{ 
    foreach (MethodInfo methodInfo in type.GetMethods()) 
    { 
     var attributes = methodInfo.GetCustomAttributes(true); 
     foreach (var attr in attributes) 
     { 
      if (attr.ToString() == "NUnit.Framework.TestAttribute") 
      { 
       var methodName = methodInfo.Name; 
       // Do stuff. 
      } 
     } 
    } 
} 
+0

這工作。如果你想獲得當前運行的測試類的測試計數而不是整個dll,請添加以下代碼:if(TestContext.CurrentContext.Test.ClassName.Contains(type.Name)) {... –