One-time initialization for NUnit
C#.NetNunitC# Problem Overview
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 database 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.
C# Solutions
Solution 1 - C#
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.
Solution 2 - C#
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()
{
}
}
Solution 3 - C#
https://github.com/nunit/docs/wiki/SetUpFixture-Attribute">NUnit 3:
[SetUpFixture]
public class TestLogging
{
[OneTimeSetUp]
public void Setup()
{
DoStuff();
}
}