Stub members
Stub a member
A stub replaces every access its selection matches with the answers your test sets. The real member never runs, and
everything outside the selection runs for real. With nothing declared, a stub does the C# default: a call or read
returns default, and a void call or a write does nothing.
Stub.Method(() => Object.Destroy(Arg.Any<Object>())); // nothing is destroyed
Stub.Property(() => Camera.main); // returns null
Stub.Field(() => sensor.distance); // reads return 0, writes are dropped
A stub handles both the reads and the writes of a
field, property or indexer: Returns decides its reads, Do its writes.
A stub also records each access it replaces, as a spy does. For more information, refer to Check what the code under test did.
Return a result
Returns sets what a call or read returns. Several values form a sequence, one per access, and the last
one repeats:
Stub.Property(() => Time.deltaTime).Returns(0.016f);
Stub.Method(() => Random.Range(0, 10)).Returns(3, 7, 1); // 3, 7, 1, 1, 1...
A selection through a chain, such as () => player.weapon.Fire(), runs a sequence for each instance
it reaches: a new weapon starts again from the first value.
A lambda computes the result at each access. It takes no parameters, or what the access passes: a call's arguments, or an indexer's indices, in order:
Stub.Method(() => Physics.Raycast(Arg.Any<Vector3>(), Arg.Any<Vector3>(), Arg.Any<float>()))
.Returns((Vector3 origin, Vector3 direction, float distance) => origin.y > 0f);
Stub.Indexer(() => level.grid[Arg.Any<int>(), Arg.Any<int>()]).Returns((int x, int y) => (x + y) % 2 == 0 ? Tile.Wall : Tile.Floor);
Write each parameter's type, as above: C# can't infer it from the selection, and code analysis offers the fix. Code analysis also reports parameters that don't fit the member.
To return null, cast it to the member's type, also inside a sequence: Returns((Camera)null),
Returns(camera, (Camera)null). Code analysis offers the fix.
Change a stub during a test
A stub is an object you can keep. Calling Returns or Do again replaces its answer
from then on:
StubbedProperty<float> deltaTime = Stub.Property(() => Time.deltaTime).Returns(0.016f);
player.Tick();
deltaTime.Returns(0.1f);
player.Tick();
Once a later declaration covers the same accesses, such as a Real, calling Returns again
doesn't bring the stub back: declare it again. For more information, refer to
Go back to the real member.
Throw an exception
A throw expression in the answer makes the access throw:
Stub.Method(() => PlayerPrefs.Save()).Do(() => throw new IOException());
Stub.Property(() => Camera.main).Returns(() => throw new InvalidOperationException());
Stub.Method(() => File.ReadAllText(Arg.Any<string>()))
.Returns((string path) => path.EndsWith(".corrupt") ? throw new IOException() : "{}");
Replace a void call or a write
Do replaces a call with no result. It takes the same parameter forms as Returns:
List<object> logged = new();
Stub.Method(() => Debug.Log(Arg.Any<object>())).Do((object message) => logged.Add(message));
On a field, a property or an indexer, Do replaces each write, and takes nothing, or the value written
(after the indices for an indexer). A stub's reads and writes never reach the real member, so an answer that checks or changes the value keeps that value in a variable of your test:
float volume = 1f;
Stub.Property(() => settings.Volume).Returns(() => volume).Do((float value) =>
{
if (value > 1f)
throw new ArgumentOutOfRangeException();
volume = value;
});
When the member should hold what the code writes, use a fake instead. For more information, refer to Fake fields and properties.
Out and ref parameters
An answer writes out and ref arguments through parameters with the same
modifier:
Stub.Method(() => Physics.Raycast(Arg.Any<Ray>(), out Arg.Any<RaycastHit>(), Arg.Any<float>()))
.Returns((Ray ray, out RaycastHit hit, float max) =>
{
hit = new RaycastHit { point = ray.origin, distance = 1f };
return true;
});
Stub every instance
On a table, EachReturns and EachDo set an
answer for every instance, and the lambda can take the instance first:
StubbedMethodTable<GameObject, Rigidbody> bodies = Stub.Method((GameObject go) => go.GetComponent<Rigidbody>())
.EachReturns((GameObject go) => lookup[go]);
bodies[boss].Returns(bossBody); // this one instance answers differently
The last answer set wins for each instance: one set on bodies[boss] holds until the table sets a new
one for every instance. A sequence runs per instance.
Stub a constructor
A stub on a constructor replaces the new in the code under test, and returns the object you give it:
Stub.Constructor(() => new SaveSystem()).Returns(testSaveSystem);
Without Returns, the new returns null, which code never expects; code
analysis warns about it. Only a new in the code under test is replaced: an object Unity creates, such as with
AddComponent, is recorded but built for real.
Make an object read as destroyed
User-defined operators and conversions are methods too. UnityEngine.Object checks for a destroyed
object with its == operator and its bool conversion, so a test can make an object read as
destroyed without destroying it:
Stub.Method(() => (bool)enemy).Returns(false);
Stub.Method(() => enemy == null).Returns(true);
enemy != null calls a separate operator, which needs a selection of its own. is null and
?. call no operator, so no stub reaches them.
Stub some calls and not others
A stub replaces only the accesses its matchers match, so a narrow selection stubs part of a member:
// Downward raycasts miss; every other raycast is real.
Stub.Method(() => Physics.Raycast(Arg.Any<Vector3>(), Vector3.down, Arg.Any<float>())).Returns(false);
When several stubs or fakes match an access, the last one declared decides. A spy never decides: it records alongside them. A broad default followed by a narrow override reads in order:
Stub.Method(() => Physics.Raycast(Arg.Any<Vector3>(), Arg.Any<Vector3>(), Arg.Any<float>())).Returns(true);
Stub.Method(() => Physics.Raycast(Arg.Any<Vector3>(), Vector3.down, Arg.Any<float>())).Returns(false);
In the reverse order, the broad stub hides the narrow one; code analysis points it out, and so does a warning in the Console. To make part of a broad stub real again, refer to Run members for real.