skip to content

In NUnit 5, what is the difference between [SetUp] and [OneTimeSetUp], and when does each one run?

level: juniorimportance: must knowfreq 66%

answer

  1. how often each method fires
  2. the matching teardown attributes
  3. base-class setup order
  4. a failing setup and the test body
  5. the 'OneTimeSetUp:' failure prefix

basics

~10 s

In NUnit, [SetUp] runs before every test in a fixture and [TearDown] after each one; [OneTimeSetUp] runs once before the fixture's first test and [OneTimeTearDown] once after its last, for expensive shared resources.

solid answer

~40 s

`[SetUp]` marks a method NUnit calls before **each** test method (and before each `[TestCase]` row) in the fixture, with `[TearDown]` called after each one, so every test starts from fresh state. `[OneTimeSetUp]` runs **once** per fixture before any of its tests, and `[OneTimeTearDown]` once after the last, which suits costly work such as building a rule table or starting a server. Setup in a base class runs before the derived class's setup, and teardown runs in the reverse order. If a `[SetUp]` throws, the test body is skipped and the test fails at its setup, but `[TearDown]` still runs for that level. If `[OneTimeSetUp]` throws, every test in the fixture is reported as failed with a message starting `OneTimeSetUp:`. Both may be `async Task`; `async void` is rejected.

code

csharp · 18 lines
csharp
[TestFixture]
public class QuoteServiceTests
{
    private TestRateServer _server = null!;
    private QuoteService _service = null!;

    [OneTimeSetUp]
    public async Task StartServer() => _server = await TestRateServer.StartAsync();

    [SetUp]
    public void NewService() => _service = new QuoteService(_server.BaseAddress);

    [TearDown]
    public void ResetServer() => _server.ClearRecordedRequests();

    [OneTimeTearDown]
    public async Task StopServer() => await _server.DisposeAsync();
}

go deeper

for a junior

Recall the four attributes and how often each fires: per test for [SetUp]/[TearDown], once per fixture for [OneTimeSetUp]/[OneTimeTearDown].

for a middle

Explain the ordering across a base class and a derived class, and what NUnit does to the test body and teardown when a setup method throws.

for a senior

Show the judgement: shared, read-only, expensive resources go in one-time setup; anything a test mutates is rebuilt per test, or tests start depending on run order.

for a principal

Frame setup placement as a cost-versus-isolation decision for the whole suite, and set a convention reviewers can check rather than leaving it to each fixture's author.

## The four lifecycle attributes An NUnit **fixture** is a class that holds tests. NUnit gives it four attributes that mark methods to run around those tests. They live in the `NUnit.Framework` namespace, in the `NUnit` package. | Attribute | Runs | Typical use | |---|---|---| | `[SetUp]` | before **every** test method or test case | fresh objects, reset counters, a new calculator | | `[TearDown]` | after **every** test method or test case | dispose per-test resources, delete temp files | | `[OneTimeSetUp]` | **once**, before the first test in the fixture | load a rate table, start a container, open a shared client | | `[OneTimeTearDown]` | **once**, after the last test in the fixture | stop or dispose what `[OneTimeSetUp]` created | A parameterised method counts as many tests: each `[TestCase]` row gets its own `[SetUp]` and `[TearDown]` call. ## The order NUnit follows For a fixture with two tests, the calls go in this order: 1. `[OneTimeSetUp]` methods (base class first, then derived). 2. For the first test: `[SetUp]` (base first), the test body, `[TearDown]` (derived first). 3. For the second test: the same `[SetUp]`, body, `[TearDown]` sequence. 4. `[OneTimeTearDown]` methods (derived first, then base). NUnit builds one setup/teardown level per class in the inheritance chain and wraps them so the **base class's setup runs outermost**. Teardown unwinds in reverse, so a derived class can rely on whatever its base prepared and clean up before the base does. ## What happens when setup fails - **A `[SetUp]` throws or an assertion in it fails.** NUnit records the failure against the setup site and **does not run the test body**. The `[TearDown]` for that level still runs, because NUnit runs teardown for any level whose setup it started. That is why teardown code should tolerate half-initialised state (null checks before `Dispose`). - **A `[OneTimeSetUp]` throws.** Nothing in the fixture can run meaningfully, so NUnit marks **every child test** with the parent's failure and a message that begins `OneTimeSetUp:`. A report full of identical failures with that prefix points at the one-time setup, not at the tests. - **An `async void` setup method.** NUnit refuses it, because it cannot await such a method. Use `async Task` for asynchronous setup and NUnit will await it. ## Choosing between them The trade-off is **isolation against cost**. - Use `[SetUp]` when tests mutate what they use. A shipping-cost calculator that caches the last quote, or a list the test appends to, must be rebuilt for each test or one test's leftovers change the next test's result. - Use `[OneTimeSetUp]` for read-only or expensive things: parsing a large rate card, starting an external dependency, creating an `HttpClient` against a test server. The saving is real when a fixture holds dozens of cases. - Do not move mutable state into `[OneTimeSetUp]` just to make a slow suite faster. Tests then depend on the order they run in. - Pair them: anything a `[OneTimeSetUp]` opens is closed in `[OneTimeTearDown]`; anything a `[SetUp]` opens is closed in `[TearDown]`. By default NUnit creates **one instance of the fixture class** for all its tests, so fields assigned in `[OneTimeSetUp]` are visible to every test. Fixture life cycles that change that, and what they forbid, belong with the parallel-execution topic. ## Mistakes interviewers listen for - **Confusing the two names.** Saying `[SetUp]` runs "once at the start" is the most common slip; that is `[OneTimeSetUp]`. - **Expecting the test to run after a failed setup.** NUnit skips the body, so a broken `[SetUp]` shows up as many failures with the same setup message, not as assertion failures. - **Teardown that assumes setup finished.** Because teardown still runs after a setup exception, `_server.Dispose()` on a null field turns one failure into two. - **Hidden ordering.** Reading from a field that only an earlier test assigns works when tests run in one order and breaks in another. If a test needs it, `[SetUp]` must create it. - **Constructors as setup.** A fixture constructor runs when NUnit creates the instance, not before each test; with the default single instance it runs once, so it cannot replace `[SetUp]`. - **Leaking resources.** A container or file handle opened in `[OneTimeSetUp]` without a `[OneTimeTearDown]` outlives the fixture and can lock files or ports for the next one. ## A shipping-cost example ```csharp [TestFixture] public class ShippingCostCalculatorTests { private RateCard _rates = null!; private ShippingCostCalculator _calculator = null!; [OneTimeSetUp] public async Task LoadRateCard() => _rates = await RateCard.LoadAsync("rates.json"); // expensive, read-only [SetUp] public void NewCalculator() => _calculator = new ShippingCostCalculator(_rates); // fresh per test [Test] public void Domestic_two_kilos_costs_6_90() => Assert.That(_calculator.Calculate(2m, Zone.Domestic, express: false), Is.EqualTo(6.90m)); } ``` The rate card is loaded once; the calculator, which may keep per-quote state, is rebuilt before each test. The same split is the answer to most "why is my suite slow" and "why do my tests pass alone but fail together" questions about NUnit fixtures.

  • If a [SetUp] method throws, does the matching [TearDown] still run?
    Yes. NUnit runs teardown for every inheritance level whose `[SetUp]` it started, even if that setup then threw. The test body is skipped and the test is reported as failed at setup. Teardown code should therefore cope with fields that were never assigned, for example by checking for null before disposing.
  • Why does an NUnit report show every test in a fixture failing with a message that starts 'OneTimeSetUp:'?
    Because the fixture's `[OneTimeSetUp]` threw. NUnit cannot run any child test without it, so it marks each child with the parent's failure and prefixes the message with `OneTimeSetUp:`. Fix the one-time setup, not the individual tests.
  • Can NUnit setup methods be asynchronous?
    Yes, if they return `Task` (or another awaitable): NUnit awaits an `async Task` `[SetUp]` or `[OneTimeSetUp]` before running tests. An `async void` setup method is rejected, because NUnit has nothing to await and could not observe its exceptions.

  • [SetUp] runs once per fixture, before the first test only
  • [OneTimeSetUp] runs again before each [TestCase] row
  • A derived class's [SetUp] runs before its base class's [SetUp]
  • If [SetUp] throws, NUnit still runs the test body
  • Mutable per-test objects belong in [OneTimeSetUp] to speed the suite up
  • async void is fine for an NUnit setup method