In NUnit 5, a banking-library fixture marked [Parallelizable(ParallelScope.All)] fails intermittently on a field assigned in [SetUp]; why, and how does [FixtureLifeCycle(LifeCycle.InstancePerTestCase)] fix it?
answer
- one fixture object by default
- LifeCycle.SingleInstance
- a new instance per test case
- static-only one-time setup
- Dispose after each test
basics
~20 sNUnit shares one fixture instance across all its tests by default, so with test-level parallelism two tests' [SetUp] calls overwrite the same field. InstancePerTestCase builds a fresh instance per test, which then requires static [OneTimeSetUp] and [OneTimeTearDown].
solid answer
~40 sThe default `LifeCycle.SingleInstance` means NUnit constructs **one** object of the fixture class and runs every test on it. Under `ParallelScope.All` (or `Children`) two tests run at once on that object: test A's `[SetUp]` assigns `_account`, test B's `[SetUp]` replaces it, and test A asserts against B's account, so it fails only when the timing overlaps. `[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]`, on the class or the assembly, makes NUnit construct a **new instance for every test case**, run `[SetUp]`, the test and `[TearDown]` on it, and dispose it afterwards if it is `IDisposable`. Instance fields stop being shared. The cost: `[OneTimeSetUp]` and `[OneTimeTearDown]` must be **static**, otherwise the fixture fails with "Only static OneTimeSetUp and OneTimeTearDown are allowed for InstancePerTestCase mode", and anything genuinely shared moves to static fields that must be thread-safe.
code
csharp · 24 lines[Parallelizable(ParallelScope.All)]
[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]
public class TransferServiceTests : IDisposable
{
private static ExchangeRates _rates = null!; // shared, read-only
private Account _source = null!; // per test
private readonly InMemoryLedger _ledger = new(); // per test
[OneTimeSetUp]
public static void LoadRates() => _rates = ExchangeRates.LoadFixed();
[SetUp]
public void OpenAccount() => _source = new Account(100m, _ledger);
[TestCase(30)]
[TestCase(70)]
public void Withdrawal_reduces_balance(decimal amount)
{
_source.Withdraw(amount);
Assert.That(_source.Balance, Is.EqualTo(100m - amount));
}
public void Dispose() => _ledger.Dispose(); // after each test
}go deeper
Recall that NUnit uses one fixture instance for all its tests unless told otherwise, and that [FixtureLifeCycle] changes it.
Explain how a shared instance plus ParallelScope.Children lets one test's [SetUp] overwrite another's fields, and what InstancePerTestCase changes in construction and disposal.
Diagnose the intermittent failure from its pattern, apply InstancePerTestCase with static one-time setup, and list the shared state it does not isolate.
Decide whether a suite adopts instance-per-test as the assembly default, weighing construction cost and static-state discipline against safer parallelism.
## The default: one fixture object When NUnit runs a fixture it normally creates **one instance** of the fixture class and runs every test method and test case on it. This is `LifeCycle.SingleInstance`, the default when no `[FixtureLifeCycle]` attribute is present. The sequence is: 1. Construct the fixture once. 2. Run `[OneTimeSetUp]`. 3. For each test: `[SetUp]`, the test body, `[TearDown]`, all on the same object. 4. Run `[OneTimeTearDown]`, then dispose the fixture once if it is `IDisposable`. When tests run one at a time this is harmless: `[SetUp]` reinitialises the fields before each test. It also lets `[OneTimeSetUp]` store expensive objects in instance fields. ## What parallelism breaks `ParallelScope.Children` or `ParallelScope.All` on the fixture lets its tests run **at the same time**. With a single instance they now share every instance field: | Time | Test A (worker 1) | Test B (worker 2) | |---|---|---| | t1 | `[SetUp]`: `_account = new Account(100m)` | | | t2 | | `[SetUp]`: `_account = new Account(500m)` | | t3 | `_account.Withdraw(30m)` acts on B's account | | | t4 | asserts balance 70, sees 470 | asserts balance 500, sees 470 | The failure depends on timing, so it appears and disappears between runs and machines. Typical symptoms: - assertions that see another test's values; - `NullReferenceException` because a `[TearDown]` cleared a field another test is using; - collections modified while being enumerated; - mocks that report calls made by a different test. ## The fix: one instance per test case ```csharp [Parallelizable(ParallelScope.All)] [FixtureLifeCycle(LifeCycle.InstancePerTestCase)] public class TransferServiceTests ``` With `LifeCycle.InstancePerTestCase` NUnit **constructs a new fixture object for every test case** (every `[TestCase]` row too), runs `[SetUp]`, the test and `[TearDown]` on it, and **disposes it after that test** if the class implements `IDisposable`. Two tests can no longer see each other's instance fields, so test-level parallelism becomes safe for state held in fields. The attribute can be placed on a fixture class or on the assembly (`[assembly: FixtureLifeCycle(LifeCycle.InstancePerTestCase)]`) and is inherited by derived fixtures. ## What it costs - **One-time setup must be static.** There is no single instance to hold one-time state, so NUnit only accepts static `[OneTimeSetUp]` and `[OneTimeTearDown]` methods; an instance method fails the fixture with "Only static OneTimeSetUp and OneTimeTearDown are allowed for InstancePerTestCase mode." - **Shared state becomes explicit.** Whatever was genuinely shared (a loaded exchange-rate table, a test server) moves to static fields, which parallel tests now read concurrently. Keep them **read-only** or thread-safe. - **More constructions.** The constructor runs once per test case; heavy work belongs in static one-time setup, not in the constructor. - **It fixes only instance state.** Static fields, files, environment variables, the current culture and external systems are still shared between parallel tests. ## Alternatives - Keep `SingleInstance` and use `ParallelScope.Self` or `Fixtures` only, so tests inside each fixture stay sequential. - Remove instance fields altogether: build the objects inside each test with a local factory method. - Mark the fixture `[NonParallelizable]` if it touches a resource that cannot be isolated. ## Class level or assembly level? | Placement | Effect | When it fits | |---|---|---| | `[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]` on a class | only that fixture gets an instance per test | migrating fixture by fixture as each one moves to `ParallelScope.All` | | `[assembly: FixtureLifeCycle(LifeCycle.InstancePerTestCase)]` | every fixture in the assembly | new suites that keep one-time state static from the start | An assembly-wide switch on an existing suite turns every instance `[OneTimeSetUp]` into a failing fixture at once, so large suites usually migrate class by class. ## Diagnosing it in a banking suite 1. Notice the pattern: failures that vanish when the test is run alone or when parallelism is turned off. 2. Check the fixture's scope (`Children` or `All`) and its life cycle (no `[FixtureLifeCycle]` means a single instance). 3. List the instance fields that `[SetUp]` assigns or tests mutate. 4. Apply `InstancePerTestCase`, make one-time setup static, and re-run under parallel load to confirm.
- With InstancePerTestCase, when is an IDisposable NUnit fixture disposed?After each test case, because each test has its own instance. Under the default `SingleInstance` life cycle the single instance is disposed once, after all the fixture's tests and its one-time teardown have run.
- Does InstancePerTestCase make every NUnit test safe to run in parallel?No. It isolates instance fields only. Static fields, including those set in static `[OneTimeSetUp]`, files, environment variables, culture settings and external systems are still shared, so they must be read-only, thread-safe or the fixture must stay `[NonParallelizable]`.
- Why does NUnit reject an instance [OneTimeSetUp] under InstancePerTestCase?One-time setup runs once for the fixture, but with a new instance per test there is no single object for it to initialise; fields it set would be invisible to the tests. NUnit therefore requires static one-time setup and teardown and fails the fixture otherwise.
- NUnit creates a new fixture instance for every test by default
- [SetUp] makes instance fields safe under ParallelScope.Children
- InstancePerTestCase also isolates static fields between tests
- Instance [OneTimeSetUp] methods still work with InstancePerTestCase
- An IDisposable fixture under InstancePerTestCase is disposed once at the end
- The intermittent failure means a race in the banking code itself