One-time initialization for NUnit

NUnit 3:

[SetUpFixture]
public class TestLogging
{
    [OneTimeSetUp]
    public void Setup()
    {
        DoStuff();
    }
}

Create a class (I call mine Config) and decorate it with the [SetUpFixture] attribute. The [SetUp] and [TearDown] methods in the class will run once.

[SetUpFixture]
public class Config
{
    [SetUp]  // [OneTimeSetUp] for NUnit 3.0 and up; see http://bartwullems.blogspot.com/2015/12/upgrading-to-nunit-30-onetimesetup.html
    public void SetUp()
    {
    }

    [TearDown]  // [OneTimeTearDown] for NUnit 3.0 and up
    public void TearDown()
    {
    }
}

The [SetUpFixture] attribute allows you to run setup and/or teardown code once for all tests under the same namespace.

Here is the documentation on SetUpFixture. According to the documentation:

A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly.

So if you need SetUp and TearDown for all tests, then just make sure the SetUpFixture class is not in a namespace.

Alternatively, you could always define a static class strictly for the purpose of defining “global” test variables.

Tags:

C#

.Net

Nunit