Wednesday, November 28, 2012

Running the same NUnit tests multiple times, using different profiles

One thing I really miss in NUnit is an easy way of running the same tests multiple times using different profiles.  Ideally, there should be some way to create an abstract TestContext helper class and adding an instance of this class either as property on your [TestFixture] class or as an argument on your [Test] method.  Then, you would provide multiple implementations of the TestContext and have NUnit automatically run your tests with each of these implementations.

However, I found I cool workaround for this: you can make your test fixture class abstract and put the [TestFixture] attribute on each implementation.

I'm using this technique in Mono's WCF metadata unit tests: mcs/class/System.ServiceModel/Test/MetadataTests/ImportTests.cs is the main test fixture class and the tests inside it are run three times using a different TestContext:

  1. ImportTests_CreateMetadata.cs creates a new MetadataSet programmatically
  2. ImportTests_LoadMetadata.cs loads it from an XML file
  3. ImportTests_RoundTrip.cs creates a new MetadataSet programmatically, exports it into an XML string, then imports it back from that string
You can also make your [Test] methods virtual in the base class, then override it and add [Category] or other nunit attributes to it.