How to find dll files containing nunit tests

我只是一个虾纸丫 提交于 2019-12-10 10:00:55

问题


I have a folder with many dlls. One of them contains nunit tests (functions marked with [Test] attribute). I want to run nunit test from c# code. Is there any way to locate the right dll?

thank you


回答1:


You can use Assembly.LoadFile method to load a DLL into an Assembly object. Then use the Assembly.GetTypes method to get all the types defined in the assembly. Then using the GetCustomAttributes method you can check if the type is decorated with the [TestFixture] attribute. If you want it quick 'n dirty, you could just call .GetType().ToString() on each attribute and check if the string contains "TestFixtureAttribute".

You can also check for the methods inside each type. Use the method Type.GetMethods to retrieve them, and use GetCustomAttributes on each of them, this time searching for "TestAttribute".




回答2:


Just in case somebody needs working solution. As you can't unload assemblies, which were loaded this way, it's better to load them in another 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);


来源:https://stackoverflow.com/questions/13663068/how-to-find-dll-files-containing-nunit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!