Unit Testing with NUnit in Visual C# 2010 Express

My favorite environment for running NUnit unit tests during the development process is definitely Unit Test Runner in CodeRush. I just love the way I can run the tests and see the results directly in the source code editor.

When I just recently had to get a usable development environment up and running with Visual C# 2010 Express, I had to find a different solution since extensions are not supported in the Express SKUs of Visual Studio which means that neither CodeRush nor TestDriven.NET can be used in this case.

The first step is pretty obvious: add the NUnit GUI runner as an external tool to the Tools menu. Configuring it that way even automatically opens the selected project in NUnit to really minimize the effort needed. Just make sure that you add both the x64 and x86 versions of the tool if you have 64-bit Windows. You'll need the second one if you compile your project for x86 which is the default setting in Visual Studio 2010. If you try to open it in the x64 version of NUnit you'll only get a cryptic FileNotFoundException from NUnit.

Assembly Not Loaded

This setup works just fine as long as you only need to run the tests. But sooner or later you'll want to debug one of them to see why it isn't working as expected. This is when you'll start to miss the functionality of attaching the debugger to an external process (NUnit in this case).

Fortunately I stumbled across a great idea how to circumvent this limitation: start the test runner directly inside your own test project. I had some problems getting it to work exactly like this and I also didn't like the idea of putting this code directly in the test assembly, so I've come up with a small modification. I added another Console Application project to my solution which I use only to start the test runner. I also changed the code to run NUnit in a separate AppDomain to give me more control over it.

class Program
{
    private static readonly string nunitFolder = 
        @"C:\Program Files (x86)\NUnit 2.5.9\bin\net-2.0";

    public static void Main()
    {
        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationBase = nunitFolder;
        setup.ConfigurationFile = Path.Combine(nunitFolder, "NUnit.exe.config");

        AppDomain nunitDomain = AppDomain.CreateDomain("NUnit", null, setup);
        nunitDomain.ExecuteAssembly(Path.Combine(nunitFolder, "NUnit.exe"),
            new string[] { Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                @"..\..\..\Tests\bin\Debug\Tests.dll") });
    }
}

You also might have noticed that I am running the GUI runner instead of console runner. It works better for me because I can select the test I want to debug instead of just blindly running all of them and waiting for the right one to start and hit my breakpoint. You can run the console runner just the same if you prefer.

Copyright
Creative Commons License