'Nunit - Getting a list of test cases in the testfixture

I have a large suite of test cases. I want to run all the tests in the testfixtures, one at a time. Running them all in one batch in NUnit does not do what I want.

To do this, I want to get all the test cases' names in a list and loop through them. Any pointers?



Solution 1:[1]

You could try reflecting the assembly and pulling out all the methods that have the [Test] attribute:

List<MethodInfo> testMethods = new List<MethodInfo>();
Assembly x = Assembly.LoadFile("CompiledTests");
Type[] classes = x.GetExportedTypes();
foreach (Type type in classes)
{
    MethodInfo[] methods = type.GetMethods();
    foreach (MethodInfo methodInfo in methods)
    {
        if (methodInfo.GetCustomAttributes(typeof(TestAttribute), true).Length == 1)
        {
            testMethods.Add(methodInfo);
        }
    }
}

Solution 2:[2]

Another alternative would be to use the implementation used by NUnit VS Adapter: https://github.com/nunit/nunit-vs-adapter/blob/master/src/NUnitTestAdapter/NUnitTestDiscoverer.cs

Basically you can use built in NUnit logic to find out what Test Cases there are. The sample code above is from NUnit 2, but I think something similar can work for NUnit 3 as well (otherwise, how would a test adapter find the test cases ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 breed052
Solution 2 ohnezahn