简体   繁体   中英

How to find dll files containing nunit tests

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

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM