NUnit global initialization - bad idea?

Viewed 16756

We need some global one time setup code in our test suite. We can do it more than once but it takes quite some time.

  • It's required by all fixtures so [TestFixtureSetUp] does not work. It has to run before all [TestFixtureSetUp] code.

  • Put it in Main() since we keep test assemblies as executables. However Main doesn't get executed under GUI client.

  • Creating a separate class with a static constructor for initialization only works when you reference the class which we do not favor doing in each and every class.

  • Inheriting all test fixtures from a base class and adding a static constructor to it causes multiple calls to the init code.

Now given the circumstances, I have two questions:

1) Is "global setup" a very bad idea that it's not supported by NUnit?

2) What's the least painful, most common way to achieve this?

5 Answers

Starting from NUnit 3.0, the Setup attribute is no longer supported inside classes marked with the SetUpFixture attribute. The current valid syntax is:

  [SetUpFixture]
  public class MySetUpClass
  {
    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
      // ...
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
      // ...
    }
  }

The OneTimeSetUp method in a SetUpFixture is executed once before any of the fixtures contained in its namespace. The OneTimeTearDown method is executed once after all the fixtures have completed execution.

Current SetUpFixture documentation page

As stated in my comment, you can achieve assembly wide init by using a SetUpFixture located on the assembly level. I needed this to turn off the UI on the default trace listener:

[SetUpFixture]
public class AssemblySetup
{
    [SetUp]
    public void Setup()
    {
        var traceListener = Debug.Listeners.Cast<TraceListener>().FirstOrDefault(listener => listener is DefaultTraceListener) as DefaultTraceListener;

        if (traceListener != null)
            traceListener.AssertUiEnabled = false;
    }
}

More about assembly or namespace setup: http://www.nunit.org/index.php?p=setupFixture&r=2.4

Note: As pointed out by others, don't use this to corrupt isolation between your tests.

Related