Introduction to Understudy
Overview
A unit test runs a piece of code and checks what it did. Game code is hard to test this way, because it reaches things a test can't control: the frame time, random numbers, physics, the scene, other objects' singletons. The usual answer is to rewrite the code first, hiding each of those behind an interface that a test can replace.
Understudy removes that step. A test names a member with a lambda, written as the code under test reaches it, and decides what that member does for the rest of the test. For example, this method computes how far an object moves in one frame:
public static float Step(float speed) => speed * Time.deltaTime;
A test fixes the frame time, and checks the distance:
Stub.Property(() => Time.deltaTime).Returns(0.5f);
Assert.That(Movement.Step(2f), Is.EqualTo(1f));
The lambda is called a selection. Everything it doesn't name runs for real. When the test ends, the stub ends with it.
The code under test still needs to be in an assembly definition, which the Test Framework requires with or without
Understudy, and a test can only name members it can see: make a private member internal. For more
information, refer to Set up a test assembly.
Spies, stubs, fakes and Real
A test double is anything that stands in for a member during a test. Understudy has three kinds of test double,
and Real, which declares that a member runs for real:
| Class | What happens to the member | Records what the code under test did |
|---|---|---|
Spy | Runs for real. | Yes |
Stub | Is replaced with the answers your test sets with Returns and Do. With nothing declared, it does the C# default: a call or read returns default, a void call or write does nothing. | Yes |
Fake | Is replaced with a working stand-in: a field or property keeps the values the code under test writes, an event keeps the handlers the code under test subscribes. | Yes |
Real | Runs for real on purpose, even where a stub or fake was declared before. | No |
Each class has an entry point for each kind of member it covers, such as Stub.Method or
Fake.Field. For the full list, refer to Choose the entry point.
A test checks what a double recorded with ordinary NUnit constraints. Spying on a caught exception has its own entry point, Spy.Catch. For more information, refer to
Spy on caught exceptions.
Woven code
Understudy rewrites your assemblies when the Editor compiles them, so that each access to a member first checks whether a test has a spy, stub or fake on it. This rewriting is called weaving, and code it rewrote is woven.
The game you release is unchanged: a player build without tests is never woven and contains none of Understudy, and the build fails if woven code ever reaches it. In the Editor, outside a test, woven code behaves as it did before: no double applies, and each access costs one extra check. For more information, refer to Woven code.
Your test assemblies aren't woven. A test's own read of a member reaches the real one, even while a stub or fake
covers it: the double decides what the code under test sees, and the test checks it through the double, such as a fake's
Value.
Leak detection
A test that reads the real clock or a real random number passes or fails depending on when and where it runs. A test that writes a static field changes what the next test sees. Understudy calls these leaks, and logs a warning with the line that caused each one:
Leak in EnemyTests.Spawns: Random.Range(int, int) ran for real at Enemy.cs:42. Stub it, or declare it real with Real.
A member the test spies on, stubs, fakes or declares Real never leaks. For more information, refer to
Detect leaks.
Compared with other mocking libraries
NSubstitute and Moq create stand-in objects, and the code under test must receive those objects instead of the real ones.
Understudy replaces members where the code under test reaches them, so it also covers static members, engine types, fields,
events and new, and the code under test keeps its real objects. Other differences to expect:
- The test itself isn't woven: a read of a member in the test gets the real value. Check what happened through the
double, such as a fake's
Valueor a stub'sCalls. - A stub has no automatic values: with nothing declared, it returns the C# default, so a stubbed method that returns
a
Taskreturnsnull. Give itReturns(Task.CompletedTask). - Doubles need no cleanup, and a double declared in
[OneTimeSetUp]starts fresh in every test. Argis in theUnderstudynamespace. In a file that also hasusing NSubstitute;, addusing Arg = Understudy.Arg;.
The following table lists how common calls translate, where buy is the Stub.Method or
Spy.Method of shop.Buy:
| NSubstitute | Moq | Understudy |
|---|---|---|
Substitute.For<IShop>() | new Mock<IShop>() | Write a small class that implements IShop in the test, pass it to the code under test, and stub through the interface: Stub.Method((IShop s) => s.Price(Arg.Any<int>())). |
Substitute.ForPartsOf<Shop>() | CallBase = true | Stub only the members the test controls. Every other member runs for real. |
shop.Price(5).Returns(10) | Setup(s => s.Price(5)).Returns(10) | Stub.Method(() => shop.Price(5)).Returns(10) |
Returns(1, 2, 3) | SetupSequence(...) | Returns(1, 2, 3) |
Returns(x => (int)x[0] * 2) | Returns<int>(id => id * 2) | Returns((int id) => id * 2) |
Arg.Any<int>() | It.IsAny<int>() | Arg.Any<int>() |
Arg.Is<int>(x => x > 5) | It.Is<int>(x => x > 5) | Arg.That<int>(Is.GreaterThan(5)), or Arg.That<int>(new PredicateConstraint<int>(x => x > 5)) for any predicate |
When(...).Do(...), Arg.Do, AndDoes | Callback(...) | Do((int item) => ...) on a void method. On a method with a result, run the code inside Returns. |
Throws(new IOException()) | Throws(new IOException()) | Do(() => throw new IOException()), or Returns(() => throw new IOException()) on a method with a result |
Received(2).Buy(1) | Verify(..., Times.Exactly(2)) | Assert.That(buy.Calls, Has.Count.EqualTo(2)) |
DidNotReceive().Buy(1) | Verify(..., Times.Never()) | Assert.That(buy.Calls, Is.Empty) |
Received.InOrder(...) | MockSequence | Compare the recorded calls' Order. For more information, refer to Check the order of calls. |
| A property that keeps what is set | SetupProperty(...) | Fake.Property(() => settings.Volume, initial: 1f), read through Value |
Raise.Event(...) | Raise(...) | Fake.Event(() => shop.Sold += Arg.Ignored).Raise(...), declared before the code under test subscribes |
ClearReceivedCalls() | Invocations.Clear() | A spy created later records only what follows. |
| Strict mocks | VerifyNoOtherCalls() | No equivalent. Leak detection reports the non-deterministic calls and global writes a test didn't declare. |