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.
This attribute is to identify methods that are called once prior to executing any of the tests in a fixture. It may appear on methods of a TestFixture or a SetUpFixture. OneTimeSetUp methods may be either static or instance methods and you may define more than one of them in a fixture.
The [TestFixture] attribute denotes a class that contains unit tests. The [Test] attribute indicates a method is a test method. Save this file and execute dotnet test to build the tests and the class library and then run the tests. The NUnit test runner contains the program entry point to run your tests.
Inheritance. The SetUp attribute is inherited from any base class. Therefore, if a base class has defined a SetUp method, that method will be called before each test method in the derived class.
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.
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() { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With