When a double ends

A spy, stub, fake or Real belongs to the test or fixture that creates it, and ends with it. Tests need no attribute, base class or cleanup for it:

Created inApplies to
The test, [SetUp] or [TearDown]That test.
The fixture's constructor, a field initializer, or [OneTimeSetUp]Every test of the fixture, each starting it fresh.
[OneTimeSetUp] public void Fixture() => Stub.Property(() => Time.deltaTime).Returns(0.02f);   // every test
[SetUp]        public void Each()    => Stub.Property(() => Random.value).Returns(0.5f);      // each test
[Test] public void SlowFrame() { Stub.Property(() => Time.deltaTime).Returns(0.1f); }       // this test only

Using a double after its owner finished throws. Creating one outside an NUnit test throws too.

Every test starts fresh

A double declared for a fixture starts over in every test: its lists of recorded calls and accesses are empty, its sequences start from their first value, a fake's stored value starts at its initial value, and an event fake holds no handlers. An answer a test sets on it ends with that test:

StubbedMethod<int> roll;

[OneTimeSetUp]
public void Fixture() => roll = Stub.Method(() => Dice.Roll(6)).Returns(3);

[Test]
public void RollsHigh()
{
    roll.Returns(6);   // this test only: the next one rolls 3 again
}

Code that must write into a fixture's double before each test, such as an object subscribing to a fixture's event fake, runs in [SetUp]. A write made from [OneTimeSetUp] is discarded before the first test, with a warning in the Console.

UnityTest and async tests

A [UnityTest] coroutine or an async test owns its doubles until it completes, not until its method first returns. Doubles apply on every thread: an access from another thread belongs to the test running at that moment, so finish or join background work before the test ends. A test that enters Play mode can also reload the domain: refer to Domain reloads.

Domain reloads

A domain reload ends every double. With Unity's default settings, a test reloads the domain when it enters Play mode itself, such as an Edit mode test that yields EnterPlayMode. Play mode tests aren't affected: the Test Runner enters Play mode before they start. A reload during a test logs a warning, and a double created before it no longer applies: using it throws. Create the doubles again after the reload.

To avoid the reload instead, go to Edit > Project Settings > Editor, and under Enter Play Mode Settings, set When entering Play Mode to Reload Scene only. Your scripts' static fields then keep their values between Play mode sessions, so your scripts reset them themselves. For more information, refer to Unity's Configurable Enter Play Mode page.

Parameterized tests

A stub can take a test's parameters like any other value:

[Test]
public void FallSpeedIsFrameRateIndependent([Values(0.016f, 0.033f, 0.1f)] float deltaTime)
{
    Stub.Property(() => Time.deltaTime).Returns(deltaTime);
    // ...
}