Get List of Categories from test assembly using NUnit

posted by Bryan on

In NUnit, you can specify a category on a test method or test fixture. I needed that list in a totally different context. Here's how to do it.

You will need to reference these assemblies: nunit.core.dll, nunit.core.interfaces.dll, nunit.framework.dll, nunit.ukit.dll, nunit.util.dll.

In order to load the assembly correctly, I needed to use a .nunit project file. I had never used one before, but it made things so simple. The assembly I was loading has about 15 referenced dlls. It was ridiculous to put all the dll's in a specific directory to keep the assembly loading process smooth. I didn't have to worry about changing directories to make sure all the referenced dll's were together.

My .nunit file

<nunitproject>
<settings appbase="./directoryOfCode">
<config name="Default" binpath="" runtimeframework="v2.0">
<assembly path="myDllName.dll">
</assembly></config>
</settings></nunitproject>

My code to get the List of Categories using Nunit.

public static ArrayList GetListOfCategories(Projects.App app)
        {
            ServiceManager.Services.AddService(new SettingsService());
            ServiceManager.Services.AddService(new DomainManager());
            ServiceManager.Services.AddService(new RecentFilesService());
            ServiceManager.Services.AddService(new ProjectService());
            ServiceManager.Services.AddService(new TestLoader(new GuiTestEventDispatcher()));
            ServiceManager.Services.AddService(new AddinRegistry());
            ServiceManager.Services.AddService(new AddinManager());
            ServiceManager.Services.AddService(new TestAgency());

            ServiceManager.Services.InitializeServices();

            string fileName = Updater.convertAppToConfig(app);
            ProjectConfig config = new ProjectConfig(fileName);

            string nUnitProjectFileName = generateNUnitProjectFile(config.BaseDir, config.DllName, config.BuildDir);

            TestLoader loader = new TestLoader();
            loader.LoadProject(config.BaseDir + "\\" + nUnitProjectFileName);
            loader.LoadTest(null);

            if (loader.IsTestLoaded)
            {
                IList list = loader.GetCategories();
                return (ArrayList) list;
            }
            throw new Exception("The TestLoader.LoadTest() did not succeed, therefore you cannot get the Categories.\nError : " + loader.LastException);
        }

Leave a comment

blog comments powered by Disqus