I’ve written about running unit tests with NUnit before, via a task in a NAnt build file. While upgrading my .NET projects to .NET 4, I found out that NUnit usage needs to be slightly updated as well.
The NUnit project put out the 2.5.5 release recently. Among other things, the release has support for running tests in assemblies compiled for .NET 4. The catch is, NUnit itself appears to have been compiled for .NET 2. So you can’t just tell it to run tests in a .NET 2 assembly; you’ll get an error similar to the following:
[exec] NUnit version 22.214.171.12412 [exec] Copyright (C) 2002-2009 Charlie Poole. [exec] Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov. [exec] Copyright (C) 2000-2002 Philip Craig. [exec] All Rights Reserved. [exec] [exec] Runtime Environment - [exec] OS Version: Microsoft Windows NT 6.1.7600.0 [exec] CLR Version: 2.0.50727.4927 ( Net 2.0 ) [exec] [exec] ProcessModel: Default DomainUsage: Single [exec] Execution Runtime: net-2.0 [exec] Unhandled Exception: [exec] System.BadImageFormatException: Could not load file or assembly 'C:UsersGrantProjectsVisualStudioTimeTrakkerbuildTimeTrakker.Tests.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
I’ve abbreviated the listing: what is shown gets the point across. Note the
runtime environment section in the middle, and the error on the last line. Clearly there’s a compatibility issue at work. There is a workaround: you can instruct NUnit to run unit tests within a .NET 4 context, even though NUnit is currently built on .NET 2.
The workaround is pretty simple: when running NUnit from the console, you need to give it an extra parameter specifying the target runtime. Below is the revised
test target in my NAnt build file. Note the last argument given to the NUnit executable, telling it to run in the .NET 4 context. The full version number is necessary.
No more error at this point!
As an additional note, you can run unit tests via the NUnit GUI. If you create a NUnit project file and add a test assembly, you can edit the project settings via the
Project->Edit menu. There is a dropdown list where you can select the runtime version to use.
Curiously, if you leave it at the
Default setting, the tests execute fine. If you were to change the setting to
2.0, you’ll get an error from NUnit. If you’re targeting .NET 4, leave the setting at
Default or choose the