skip to content

In NUnit 5, what does a [SetUpFixture] do, and how does its namespace decide which fixtures its one-time setup covers?

level: seniorimportance: should knowfreq 25%

answer

  1. one-time setup above the fixtures
  2. the class's namespace is the scope
  3. no namespace means the assembly
  4. [SetUp] and [TearDown] not allowed
  5. outer namespaces run first

basics

~20 s

A [SetUpFixture] class holds [OneTimeSetUp] and [OneTimeTearDown] methods that run once around every fixture in its namespace and nested namespaces; outside any namespace it wraps the whole assembly. It may not contain [SetUp] or [TearDown].

solid answer

~40 s

A class marked `[SetUpFixture]` replaces the **namespace suite** it sits in. Its `[OneTimeSetUp]` runs once before any fixture in that namespace or a nested one, and its `[OneTimeTearDown]` once after the last of them, so it suits work shared by many fixtures: starting a database container, seeding reference data, configuring a logger. A setup fixture **outside any namespace** wraps the whole assembly. Setup fixtures in outer namespaces run before inner ones, and their teardowns run after. NUnit validates the class: it must not be abstract, needs a default constructor unless it is static, and may not declare `[SetUp]` or `[TearDown]` ("SetUp attribute not allowed in a SetUpFixture"). With parallel fixtures underneath, whatever it creates is shared by tests running at the same time, so it should be read-only or thread-safe.

code

csharp · 19 lines
csharp
namespace Bank.Tests.Integration;

[SetUpFixture]
public class IntegrationSetup
{
    public static string ConnectionString { get; private set; } = "";
    private static TestDatabase _db = null!;

    [OneTimeSetUp]
    public static async Task StartDatabase()
    {
        _db = await TestDatabase.StartAsync();
        await _db.SeedCurrenciesAsync();
        ConnectionString = _db.ConnectionString;   // read-only after this point
    }

    [OneTimeTearDown]
    public static async Task StopDatabase() => await _db.DisposeAsync();
}

go deeper

for a junior

Recall that [SetUpFixture] holds one-time setup and teardown for every fixture in its namespace, or the whole assembly when it has no namespace.

for a middle

Explain how it replaces the namespace suite, the order of nested setup fixtures, and the validation rules NUnit applies to the class.

for a senior

Use namespaces deliberately to scope expensive shared resources, and make what they create safe for fixtures that run in parallel.

for a principal

Organise the test project's namespaces so slow shared infrastructure is scoped to the suites that need it and fast unit tests never wait for it.

## Where it sits in the test tree NUnit arranges tests as a tree: the **assembly**, then one suite per **namespace**, then **fixtures** (classes), then **tests**. A fixture's `[OneTimeSetUp]` covers one class. Some setup is wider than that: a database container used by twenty fixtures, a reference-data seed, a logger configured once for the run. A class marked **`[SetUpFixture]`** provides that wider setup. When NUnit builds the tree, the setup fixture **takes the place of the namespace suite** it is declared in, and every fixture in that namespace (and in nested namespaces) becomes its child. ## Scope by namespace | Setup fixture declared in | Covers | |---|---| | no namespace (global) | every fixture in the assembly | | `Bank.Tests` | fixtures in `Bank.Tests`, `Bank.Tests.Ledger`, `Bank.Tests.Statements` and below | | `Bank.Tests.Ledger` | only fixtures in `Bank.Tests.Ledger` and below | When setup fixtures exist at several levels, they nest: for a fixture in `Bank.Tests.Ledger` the order is 1. `Bank.Tests` setup fixture's `[OneTimeSetUp]` 2. `Bank.Tests.Ledger` setup fixture's `[OneTimeSetUp]` 3. the fixture's own `[OneTimeSetUp]`, its tests, its `[OneTimeTearDown]` 4. `Bank.Tests.Ledger` setup fixture's `[OneTimeTearDown]` 5. `Bank.Tests` setup fixture's `[OneTimeTearDown]` A file-scoped namespace declaration counts the same as a block-scoped one; what matters is the namespace the class ends up in. ## Rules NUnit enforces - The class may be **static**; otherwise it must not be **abstract** and must have a **parameterless constructor**. - It may contain only one-time methods. A `[SetUp]` or `[TearDown]` method makes the setup fixture invalid with "SetUp attribute not allowed in a SetUpFixture" (or the `TearDown` equivalent), because there is no single test for them to wrap. - If its `[OneTimeSetUp]` fails, every fixture beneath it is reported as failed with a message starting `OneTimeSetUp:`, the same propagation as for a fixture's own one-time setup. ## Setup fixtures and parallel runs A setup fixture runs its one-time setup **before** any fixture beneath it is dispatched, and its teardown after all of them finish, so the resource exists for the whole namespace. What changes under parallelism is who uses it: - With `[assembly: Parallelizable(ParallelScope.Fixtures)]`, several fixtures under the setup fixture run **at the same time** and use whatever it created concurrently. - Store shared resources in **static** members (fixtures cannot see the setup fixture's instance) and make them **read-only** after setup, or thread-safe. - Give each test its own slice of a shared resource: one database container for the namespace, but a unique schema or account id per test, so parallel tests do not collide. ## A banking example A banking library's integration tests need one PostgreSQL container and a seeded currency table, used by the ledger, statement and transfer fixtures. - Put a `[SetUpFixture]` in `Bank.Tests.Integration`; its `[OneTimeSetUp]` starts the container and seeds currencies; its `[OneTimeTearDown]` stops it. - Expose the connection string through a static property. - Leave pure unit tests in `Bank.Tests.Unit`, outside that namespace, so they never wait for the container. The namespace boundary is the scoping tool: moving a fixture into a different namespace changes which one-time setup it gets. ## Setup fixture or shared base class? | Need | `[SetUpFixture]` | Base fixture class | |---|---|---| | Runs once for many fixtures | yes, once per namespace | no, its `[OneTimeSetUp]` runs once **per derived fixture** | | Per-test setup shared by fixtures | not allowed | yes, a base `[SetUp]` runs before each test | | Scope chosen by | the namespace | which classes inherit it | | Shared state reachable through | static members | inherited instance or static members | The two combine well: a setup fixture starts the expensive resource once, and a base class gives every fixture the same per-test reset against it. ## Mistakes to avoid - **Placing it in the wrong namespace.** A setup fixture in `Bank.Tests.Integration` does nothing for fixtures in `Bank.Tests.Unit`; one declared with no namespace runs for everything, including tests that do not need it. - **Putting per-test reset in it.** Per-test work belongs in each fixture's `[SetUp]`; the setup fixture runs once. - **Sharing mutable data.** A static list that tests append to becomes a race as soon as fixtures run in parallel.

  • How do you make an NUnit [SetUpFixture] apply to the whole test assembly?
    Declare the class outside any namespace. NUnit then makes it the root of the test tree, so its `[OneTimeSetUp]` runs before every fixture in the assembly and its `[OneTimeTearDown]` after all of them.
  • Can an NUnit [SetUpFixture] contain [SetUp] methods to run before each test in the namespace?
    No. NUnit marks such a setup fixture invalid with "SetUp attribute not allowed in a SetUpFixture". Only one-time setup and teardown belong there; per-test setup goes in each fixture, or in a shared base class the fixtures inherit.
  • Two NUnit fixtures under one [SetUpFixture] run in parallel. What must be true of the resource it created?
    Both fixtures use it at the same time, so it must be read-only after setup or thread-safe, and tests should take their own slice of it, such as a unique schema, account id or temp directory, instead of mutating shared data.

  • A [SetUpFixture] runs its setup before each test in the namespace
  • Its scope is chosen by the folder the file is in
  • A [SetUpFixture] with no namespace applies to no fixtures
  • [SetUp] and [TearDown] methods are allowed in a [SetUpFixture]
  • Inner namespace setup fixtures run before outer ones
  • Fixtures under one [SetUpFixture] never run in parallel