Lifecycle of a test fixture
As mentioned before, NUnit gives the developer the possibility to extract all initialization and tear-down code that multiple tests might be sharing into ad-hoc methods.
Developers can take advantage of the following facilities to streamline their fixtures
A method decorated with a
SetUp
attribute will be executed before each testA method decorated with a
TearDown
attribute will be executed after each testA method decorated with a
OneTimeSetUp
attribute will be executed before any test is executedA method decorated with a
OneTimeTearDown
attribute will be executed after all tests have been executedThe class constructor will be executed before any method and can be used to prepare fields that shouldn't be modified while executing the tests.
Additionally, developers can set up fixtures contained in a namespace and all its children by creating a class decorated with the attribute SetUpFixture
. This class will be able to contain methods decorated with OneTimeSetUp
and OneTimeTearDown
attributes.
NUnit supports multiple SetUpFixture
classes: in this case, setup methods will be executed starting from the most external namespace in and the teardown from the most internal namespace out.
Example
Let's execute all tests contained in the snippet below:
We will see the following output on the console.
Last updated