code-ninja code-ninja - 1 year ago 173
C# Question

One Time initialization for Nunit

Where should I place code that should only run once (and not once per class)? An example for this would be a statement that initializes the DB connection string. And I only need to run that once and I don't want to place a new method within each "TestFixture" class just to do that.

Answer Source

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

Here are the docs on SetUpFixture. According to the docs:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download