如何查找包含NUnit测试的dll文件

3

我有一个包含许多dll文件的文件夹。其中一个包含nunit测试(用[Test]属性标记的函数)。我想从C#代码中运行nunit测试。是否有办法找到正确的dll文件?

谢谢

2个回答

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);

我正在尝试使用你的解决方案,但是没有找到任何结果type.GetCustomAttributes(typeof(NUnit.Framework.TestFixtureAttribute), true) - Santosh M
@SantoshM 你是传递完整的 assemblyPath 还是相对路径? - VladL
是的,我提供了程序集的完整路径。 static void Main(string[] args) { Assembly testDLL = Assembly.LoadFile(@"C:\Source\Automation\bin\Debug\Automation.dll"); foreach (Type type in testDLL.GetTypes()) { Console.WriteLine(type.FullName);
if (type.GetCustomAttributes(typeof(NUnit.Framework.TestFixtureAttribute), true).Length > 0) { Console.WriteLine("--->" + type.Name); } } }
- Santosh M
@SantoshM 你的类是公共的并且使用了 NUnit.Framework.TestFixtureAttribute 属性装饰吗? - VladL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接