Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

nunit

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

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 issue is that runner.TestResult is null until you actually run the tests. I obviously don't want to run the tests at this point, I just want to get a list of which tests are in the library. After that, I will give users the ability to select a test and run it individually, passing in the test id to the RemoteTestRunner instance.

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

like image 792
Justin Avatar asked May 23 '12 16:05

Justin


2 Answers

You could use reflection to load the assembly and look for all the test attributes. This would give you all the methods that are test methods. The rest is up to you.

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

like image 167
Seth Flowers Avatar answered Oct 26 '22 23:10

Seth Flowers


Here is the code to retrieve all of the test names out of the test class library assembly:

//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);
                }
            }
like image 41
Justin Avatar answered Oct 27 '22 01:10

Justin