Selections

Every spy, stub, fake and Real takes a selection: a lambda that contains one member, written the way the code under test reaches it.

Stub.Method(() => Physics.Raycast(origin, Vector3.down, 10f));   // a method
Stub.Property(() => Camera.main);                                // a property
Fake.Field(() => player.health);                                 // a field
Spy.Indexer(() => level.grid[3, 4]);                             // an element written with []
Spy.Event(() => player.Died += Arg.Ignored);                     // an event

A selection names its outermost member: () => Object.Destroy(enemy.gameObject) selects Destroy, not gameObject.

The instance and the arguments inside the lambda are evaluated again at each access, so they see what the code under test sees. () => player.weapon.Fire() covers the weapon the player holds at that moment, a stubbed weapon included. To cover one weapon only, hold it in a local first:

Weapon starter = player.weapon;
Stub.Method(() => starter.Fire());

While a link in the chain is null, the selection covers nothing. For example, Edit mode tests often run with no keyboard connected, so Keyboard.current is null and () => Keyboard.current.spaceKey.isPressed has no key to cover. Add a keyboard in the test, and stub Keyboard.current to return it:

Keyboard keyboard = InputSystem.AddDevice<Keyboard>();
Stub.Property(() => Keyboard.current).Returns(keyboard);
Stub.Property(() => Keyboard.current.spaceKey.isPressed).Returns(true);

// ... run the code under test and check the result ...

InputSystem.RemoveDevice(keyboard);

Any other exception thrown inside the lambda also makes the selection cover nothing, and the Console shows a warning that names the member and the exception.

Choose the entry point

Each of Spy, Stub, Fake and Real has one entry point per kind of member it covers, named after it:

Entry pointSelectsSpyStubFakeReal
MethodA method, a user-defined operator or conversion: () => Random.Range(0, 10), () => enemy == nullYesYesYes
ConstructorA new: () => new SaveSystem()YesYesYes
FieldA field, readonly included: () => player.healthYesYesYesYes
PropertyA property, get-only included: () => Time.deltaTimeYesYesYesYes
IndexerAn element written with [], arrays included: () => level.grid[3, 4]YesYesYes
EventAn event, named by += or -= with Arg.Ignored: () => SceneManager.sceneLoaded += Arg.IgnoredYesYesYes

A field, a property or an element is selected as the code under test reads it, never as an assignment: its writes belong to the same spy, stub or fake. Code analysis reports a wrong entry point as an error, with a fix that writes the right one. For the list of errors, refer to Code analysis reference.

One instance or every instance

A captured variable selects that instance only, and returns one spy, stub or fake. A lambda parameter selects every instance, and returns a table: one double per instance, reached with the instance as its index.

StubbedMethod stub = Stub.Method(() => playerBody.AddForce(Arg.Any<Vector3>()));                         // this body only
StubbedMethodTable<Rigidbody> stubs = Stub.Method((Rigidbody body) => body.AddForce(Arg.Any<Vector3>()));   // every body
stubs[enemyBody].Do(() => pushed++);                                                                    // one of them
  • A table lists what was recorded on every instance. To set one answer for every instance, refer to Stub every instance.
  • A selection takes at most one parameter: the instance. On a static member, it takes none.
  • For an extension method, the instance is its this argument: (List<Enemy> list) => list.Shuffle().
  • A struct instance matches by equality, like an argument.

Match arguments

Every argument and index in a selection is a matcher:

ArgumentMatches
A value, such as 10f or Vector3.downArguments equal to it, as NUnit's Is.EqualTo compares them. Collections and params arrays compare item by item.
Arg.Any<T>()Every argument.
Arg.That<T>(constraint)Arguments that satisfy an NUnit constraint, such as Arg.That<float>(Is.GreaterThan(50f)).
Stub.Method(() => Physics.Raycast(Arg.Any<Vector3>(), Vector3.down, Arg.Any<float>())).Returns(false);

An out or ref argument is written out Arg.Any<T>() or ref Arg.Any<T>(), and never filters.

A selection covers one overload: Random.Range(0, 10) and Random.Range(0f, 1f) are different methods, and each needs a selection of its own. An optional parameter left out of a selection matches only its default value. The calls a selection doesn't match run for real. A real call to another overload of a member the test stubs or fakes is a leak. For more information, refer to Detect leaks.

A matcher stands for a whole argument: new Ray(Arg.Any<Vector3>(), dir) is an error, and so is a matcher in place of the instance or outside a selection.

Generic methods

A generic method is selected with its type arguments. (GameObject go) => go.GetComponent<Rigidbody>() covers GetComponent<Rigidbody> only, and each other type argument needs a selection of its own. A call from generic code matches too: GetComponent<T>() inside a generic Find<T> of the code under test matches when T is Rigidbody.

The type of a matcher decides which overload the selection names. Object.Instantiate has a non-generic overload, Instantiate(Object), and a generic one, Instantiate<T>(T). When the code under test passes a GameObject, C# calls the generic one, so the selection must pass a GameObject too:

GameObject enemy = Object.Instantiate(enemyPrefab);           // the code under test calls Instantiate<GameObject>

Stub.Method(() => Object.Instantiate(Arg.Any<GameObject>()));   // selects Instantiate<GameObject>: matches
Stub.Method(() => Object.Instantiate(Arg.Any<Object>()));       // selects Instantiate(Object): never matches

Virtual and interface members

A selection matches by the instance and by the method that runs, whatever type the call goes through:

  • (Weapon w) => w.Fire() covers every weapon and every override of Fire.
  • (Pistol p) => p.Fire() covers pistols only, also when the code under test calls them through a Weapon variable.
  • (IDamageable d) => d.TakeDamage(Arg.Any<int>()) covers every implementation, also when the code under test calls it on the concrete type.

A base.Fire() inside an override is part of the call it extends, not a second call. A new member that hides an inherited one is a different member.

Fields of structs

A selection can't name a field inside a struct. Select the field or property that holds the struct instead:

public struct Stats { public int health; public int armor; }
public class Player { public Stats stats; }

Fake.Field(() => player.stats.health);                                         // error UST0013
FakedField<Stats> stats = Fake.Field(() => player.stats, initial: new Stats { health = 10 });

The fake holds the whole Stats value. When the code under test runs stats.health += 5, it reads the fake's value, changes the copy and writes it back:

player.Heal(5);   // stats.health += 5
Assert.That(stats.Value.health, Is.EqualTo(15));

A struct a property returns is a copy, so its fields belong to no member. Select the property:

Stub.Field(() => enemy.transform.position.x);                                 // error UST0013
Stub.Property(() => enemy.transform.position).Returns(new Vector3(5f, 0f, 0f));

For more information, refer to Structs changed in place.

Private members

A test can't name a private member, so it can't select one. Make the member internal, and give the test assembly access with InternalsVisibleTo. For more information, refer to Reach members that aren't public.

Additional resources