Share doubles between tests
Group doubles in a class
When several tests need the same spies, stubs and fakes, create them in a plain class, in its constructor or its field initializers. The class can also hold the state its answers share, such as the keys a test holds down:
class TestInput
{
readonly HashSet<KeyCode> held = new();
public readonly StubbedProperty<Vector3> mousePosition = Stub.Property(() => Input.mousePosition);
public readonly StubbedMethod<bool> getKey;
public TestInput()
{
getKey = Stub.Method(() => Input.GetKey(Arg.Any<KeyCode>())).Returns((KeyCode key) => held.Contains(key));
}
public void Press(KeyCode key) => held.Add(key);
public void ReleaseAll() => held.Clear();
}
A test creates an instance and uses it like any double:
[Test]
public void JumpsWhenSpaceIsHeld()
{
TestInput input = new();
input.Press(KeyCode.Space);
player.Update();
Assert.That(player.IsJumping, Is.True);
}
The doubles belong to the test or fixture that creates the instance, and end with it, as every double does. The
next test that creates a TestInput gets new doubles with nothing recorded. For more information, refer
to Lifetime.
Cover one instance
To cover the members of one object only, pass that object to the constructor and select through it:
class TestEnemy
{
public readonly FakedField<int> health;
public readonly SpiedMethod hits;
public TestEnemy(Enemy enemy, int startHealth)
{
health = Fake.Field(() => enemy.health, initial: startHealth);
hits = Spy.Method(() => enemy.Hit(Arg.Any<int>()));
}
}
TestEnemy boss = new(bossEnemy, 100); // covers bossEnemy only
A selection with a lambda parameter covers every instance instead. For more information, refer to One instance or every instance.
Share one instance in a fixture
To share one instance with every test of a fixture, create it in a field initializer. Each test starts its
doubles fresh, but the class's own fields, such as held, keep their values between tests: reset them in
[SetUp].
public class PlayerTests
{
readonly TestInput input = new();
[SetUp]
public void ReleaseKeys() => input.ReleaseAll();
}
Two instances in one test
Two instances declare the same doubles twice, and they overlap like any other declarations: the instance created last answers, and the spies, stubs and fakes of both record every access. For more information, refer to Stub some calls and not others.
Share the classes between test assemblies
To use the same classes from several test assemblies, put them in an assembly definition of their own that
references Understudy, and reference it from each test assembly. That assembly needs the
UNITY_INCLUDE_TESTS define constraint, as test assemblies have. For more information, refer to
Create a test assembly.