… how to execute setup code before every TestFixture without using inheritance

Not sure how I missed this, but it came in very handy during a recent IoC refactor.

I’m sure everyone knows that about the SetUp and TearDown method attributes.  Most people also know about the TestFixtureSetUp and TestFixtureTearDown method attributes.  Let’s say you needed to run some setup code once before any tests execute.  In addition, you have ton of existing tests that don’t inherit from a base test.  Enter the SetupFixture attribute.  It provides one-time setup and teardown for all fixtures in a namespace or assembly.

Unlike the previous attributes, SetupFixture is a class attribute.  Inside a class with this attribute, you can have methods with the standard SetUp and TearDown attributes.  Asssuming the class is in a namespace, the SetUp method will run once before ALL  fixtures in the namespace.  The TearDown method will run once after ALL fixtures in the namespace.  If the SetupFixture class is not in namespace, it will affect every TestFixture in the entire assembly.  All of this happens without a base class.

Some SetupFixture class requirements:

  • Must be a publicly exported type
  • Must have a default constructor
  • Must have at most one method decorated with [SetUp] attribute
  • Must have at most one method decorated with [TearDown] attribute
  • Only one [SetupFixture] should exist per namespace.  (Haven’t tried this so not sure what happens)

Sample SetupFixture class below

namespace NUnit.Tests {
 using System;
 using NUnit.Framework;

 [SetUpFixture]
 public class MySetUpClass  {

    [SetUp]
    RunBeforeAnyTests()  {
       // ...
    }

    [TearDown]
    RunAfterAnyTests()  {
       // ...
    }
 }
}
Advertisements

~ by Bob Banks on 06/16/2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: