2012-12-01 35 views
3

我有一個帶有許多dll的文件夾。其中一個包含nunit測試(用[Test]屬性標記的功能)。我想從c#代碼運行nunit測試。有沒有辦法找到正確的DLL?如何查找包含nunit測試的dll文件

謝謝

回答

5

您可以使用Assembly.LoadFile方法將DLL加載到Assembly對象。然後使用Assembly.GetTypes方法獲取在程序集中定義的所有類型。然後使用GetCustomAttributes方法,您可以檢查類型是否用[TestFixture]屬性修飾。如果你想快速的修改,你可以在每個屬性上調用.GetType()。ToString(),並檢查字符串是否包含「TestFixtureAttribute」。

您還可以檢查每種類型中的方法。使用方法Type.GetMethods來檢索它們,並在它們每個上使用GetCustomAttributes,這次搜索「TestAttribute」。

0

以防萬一有人需要工作解決方案。由於無法卸載以此方式加載的程序集,因此最好將它們加載到另一個AppDomain中。

public class ProxyDomain : MarshalByRefObject 
    { 
     public bool IsTestAssembly(string assemblyPath) 
     { 
     Assembly testDLL = Assembly.LoadFile(assemblyPath); 
     foreach (Type type in testDLL.GetTypes()) 
     { 
      if (type.GetCustomAttributes(typeof(NUnit.Framework.TestFixtureAttribute), true).Length > 0) 
      { 
       return true; 
      } 
     } 
     return false; 
     } 
    } 

    AppDomainSetup ads = new AppDomainSetup(); 
    ads.PrivateBinPath = Path.GetDirectoryName("C:\\some.dll"); 
    AppDomain ad2 = AppDomain.CreateDomain("AD2", null, ads); 
    ProxyDomain proxy = (ProxyDomain)ad2.CreateInstanceAndUnwrap(typeof(ProxyDomain).Assembly.FullName, typeof(ProxyDomain).FullName); 
    bool isTdll = proxy.IsTestAssembly("C:\\some.dll"); 
    AppDomain.Unload(ad2); 
相關問題