Test common Unity code
In these examples, the lambda passed to Stub, Spy or Fake is a
selection, which names the member as the code under test reaches it.
Arg.Any is a matcher, which matches any argument. The values
or lambda given to Returns or Do are the stub's answer.
Test a component
In an Edit mode test, Unity doesn't call Awake, Start or Update on your
components. Create the component with AddComponent, call the methods the test needs, and destroy the
object at the end with DestroyImmediate, since Destroy isn't allowed outside Play mode:
public class Mover : MonoBehaviour
{
public float speed = 2f;
internal void Update()
{
transform.position += Vector3.right * (speed * Time.deltaTime);
}
}
[Test]
public void MovesBySpeedTimesFrameTime()
{
Stub.Property(() => Time.deltaTime).Returns(0.5f);
Mover mover = new GameObject().AddComponent<Mover>();
mover.Update();
Assert.That(mover.transform.position.x, Is.EqualTo(1f));
Object.DestroyImmediate(mover.gameObject);
}
A test can only call what it can see, and Unity messages such as Update are usually private. Make the
method internal, and give the test assembly access with InternalsVisibleTo; Unity still calls
it every frame. For more information, refer to
Reach members that aren't public. To let Unity call
Update over real frames instead, use a [UnityTest] in a Play mode test.
Fix the frame time and random values
Stub each value the test depends on. Several values form a sequence, one per call, and the last one repeats. A selection covers one overload, so match the one the code under test calls: Random.Range(-10f, 10f) calls the float overload.
Stub.Property(() => Time.deltaTime).Returns(0.02f);
Stub.Method(() => Random.Range(Arg.Any<float>(), Arg.Any<float>())).Returns(3f, -4f);
Vector3 position = spawner.PickPosition(); // new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f)): x is 3, z is -4
Replace a singleton
Fake the static field or property that holds the instance, with an instance the test creates. In an Edit mode test, AddComponent doesn't run Awake, so the component doesn't register itself and Instance stays null:
GameManager manager = new GameObject().AddComponent<GameManager>();
manager.score = 42;
Fake.Field(() => GameManager.Instance, initial: manager);
Assert.That(ScoreLabel.Text(), Is.EqualTo("Score: 42"));
Object.DestroyImmediate(manager.gameObject);
Use Fake.Field for a field, such as public static GameManager Instance;, and Fake.Property for a property. When the code under test assigns the singleton, as an Awake that writes Instance = this does, the write lands in the fake, and the real field keeps its value. For more information, refer to
Fake fields and properties.
Simulate input
Stub Input.GetKey for every key with Arg.Any, so no key reads the real keyboard, and
return true for the keys the test holds down:
Stub.Method(() => Input.GetKey(Arg.Any<KeyCode>())).Returns((KeyCode key) => key == KeyCode.Space);
Here Space is held down and every other key is up. To share pressed keys between tests, refer to Share doubles between tests.
Make a raycast hit
Stub the overload the code under test calls, here Physics.Raycast(ray, out hit, maxDistance), and
write the hit through the answer's out parameter:
Stub.Method(() => Physics.Raycast(Arg.Any<Ray>(), out Arg.Any<RaycastHit>(), Arg.Any<float>()))
.Returns((Ray ray, out RaycastHit hit, float maxDistance) =>
{
hit = new RaycastHit { point = new Vector3(0f, 2f, 0f), distance = 1f };
return true;
});
Physics.Raycast has a separate overload for each set of parameters, and a selection covers one
overload. If the code under test also calls a raycast with a layerMask, stub that overload too: a leak
warning names any overload that runs for real. For more information, refer to
Out and ref parameters.
Check that an event fired
Spy on the event, and check its raises in Invocations. A raise is recorded even when no handler is subscribed:
SpiedEvent died = Spy.Event(() => player.Died += Arg.Ignored);
player.TakeDamage(100);
Assert.That(died.Invocations, Has.Count.EqualTo(1));
With no handler subscribed, C# doesn't evaluate a raise's arguments. To check them, subscribe a handler first. For more information, refer to Check handlers and raises.
Raise an engine event
Fake the event, let the code under test subscribe to it, then raise it from the test:
FakedEvent sceneLoaded = Fake.Event(() => SceneManager.sceneLoaded += Arg.Ignored);
hud.Init();
sceneLoaded.Raise(SceneManager.GetActiveScene(), LoadSceneMode.Single);
Only subscriptions in the code under test reach the fake: a handler the test subscribes itself stays on the real event. For more information, refer to Fake events.
Test a coroutine
In an Edit mode test, run a coroutine one step at a time with MoveNext: each call runs it to its next yield. A WaitForSeconds only waits when Unity runs the coroutine, so the next step runs at once:
SpiedConstructor<WaitForSeconds> waits = Spy.Constructor(() => new WaitForSeconds(Arg.Any<float>()));
StubbedMethod<GameObject> spawned = Stub.Method(() => Object.Instantiate(Arg.Any<GameObject>()));
IEnumerator routine = spawner.SpawnAfterDelay();
routine.MoveNext(); // runs to the yield
Assert.That(waits.Calls[0].Arguments[0], Is.EqualTo(2f));
routine.MoveNext(); // runs the rest
Assert.That(spawned.Calls, Has.Count.EqualTo(1));
A stub on Time.time or Time.deltaTime doesn't shorten a WaitForSeconds, which Unity's own clock decides. To run a coroutine over real frames, use a [UnityTest] in a Play mode test.
Stub async code
Return a finished task, or an Awaitable that is already complete:
Stub.Method(() => loader.LoadAsync()).Returns(Task.FromResult(21));
Stub.Method(() => Awaitable.WaitForSecondsAsync(Arg.Any<float>())).Returns(() =>
{
AwaitableCompletionSource done = new();
done.SetResult();
return done.Awaitable;
});
An Awaitable can be awaited only once, so the answer creates a new one for each call. A test method
can be async Task, and awaits the code under test as any caller does.
Check what the code under test logs
The Test Runner fails a test that logs an error it doesn't expect. To check an error without logging it, stub Debug.LogError:
StubbedMethod logged = Stub.Method(() => Debug.LogError(Arg.That<object>(Does.Contain("corrupt"))));
save.Load("garbage");
Assert.That(logged.Calls, Has.Count.EqualTo(1));
To let the error reach the Console instead, declare it expected with Unity's LogAssert.Expect(LogType.Error, message).
Keep tests out of PlayerPrefs
Back PlayerPrefs with a dictionary the test owns, so the calls you stub never read or write the real saves:
Dictionary<string, int> prefs = new();
Stub.Method(() => PlayerPrefs.SetInt(Arg.Any<string>(), Arg.Any<int>()))
.Do((string key, int value) => prefs[key] = value);
Stub.Method(() => PlayerPrefs.GetInt(Arg.Any<string>(), Arg.Any<int>()))
.Returns((string key, int fallback) => prefs.TryGetValue(key, out int value) ? value : fallback);
GetInt(key) and GetInt(key, fallback) are different overloads: stub each one the code under test calls.
Stub a scene load
Stub SceneManager.LoadScene so that the test stays in its scene, and check which scene the code under test asked for:
StubbedMethod loaded = Stub.Method(() => SceneManager.LoadScene(Arg.Any<string>()));
flow.Win();
Assert.That(loaded.Calls[0].Arguments[0], Is.EqualTo("Level2"));
Answer a dialog in Editor code
Stub EditorUtility.DisplayDialog, so that a dialog never blocks the test run. Stub each overload the code under test calls:
Stub.Method(() => EditorUtility.DisplayDialog(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())).Returns(true);
Fill an engine type
To pass the code under test an engine type whose properties a test can't set, such as Collision, stub its reads
on every instance:
Stub.Property((Collision c) => c.gameObject).EachReturns(enemyObject);
sword.OnCollisionEnter(new Collision());
For more information, refer to Stub every instance.