Get a list of tests in the nunit library programmatically without having to run tests

I have a nunit class library containing test cases. I want to programmatically get a list of all the tests in the library, mainly the names of the tests and their test identifiers. Here is what I still have:

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

The problem is that runner.TestResult is null until you start the tests. I obviously do not want to run the tests at the moment, I just want to get a list of tests that are in the library. After that, I will give users the opportunity to select a test and run it individually by passing the test ID to the RemoteTestRunner instance.

So, how can I get a list of tests without actually running all of them?

+6
source share
3 answers

You can use reflection to load the assembly and search for all test attributes. This will give you all the methods that are testing methods. The rest is up to you.

Here is an example in msdn about using reflection to get attributes for a type. http://msdn.microsoft.com/en-us/library/z919e8tw.aspx

+6
source

Here is the code to extract all test names from the assembly of the test class library:

 //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); } } 
+4
source

Justin's answer doesn't work for me. The following does (returns all method names with the Test attribute):

 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. } } } } 
+1
source

Source: https://habr.com/ru/post/916480/


All Articles