Back to Nunit

SetUp And TearDown

docs/articles/nunit/technical-notes/usage/SetUp-and-TearDown.md

latest2.3 KB
Original Source

SetUp And TearDown

Attribute Usage

Attribute Usage by Fixture Type

TestFixtureSetUpFixture
OneTimeSetUpSupportedSupported
OneTimeTearDownSupportedSupported
TestFixtureSetUpDeprecatedNot Allowed
TestFixtureTearDownDeprecatedNot Allowed
SetUpSupportedNot Allowed
TearDownSupportedNot Allowed

How Setup and TearDown Methods Are Called

Multiple SetUp, OneTimeSetUp, TearDown and OneTimeTearDown methods may exist within a class.

Setup methods (both types) are called on base classes first, then on derived classes. If any setup method throws an exception, no further setups are called.

Teardown methods (again, both types) are called on derived classes first, then on the base class. The teardown methods at any level in the inheritance hierarchy will be called only if a setup method at the same level was called. The following example is illustrates the difference.

csharp
public class BaseClass
{
   [SetUp]
   public void BaseSetUp() { /* ... */ } // Exception thrown!

   [TearDown]
   public void BaseTearDown() { /* ... */ }
}

[TestFixture]
public class DerivedClass : BaseClass
{
   [SetUp]
   public void DerivedSetUp() { /* ... */ }

   [TearDown]
   public void DerivedTearDown() { /* ... */ }

   [Test]
   public void TestMethod() { /* ... */ }
}

Execution will proceed as follows:

  • BaseSetUp
  • BaseTearDown

rather than

  • BaseSetUp
  • DerivedTearDown
  • BaseTearDown

See also: SetUp and TearDown Changes