Quick Usage Guide

Stub, spy on and catch leaks in Unity code from a test, without changing the code.

Before you start

This guide assumes you write tests with the Unity Test Framework. If you don't, follow Write your first test in the User Manual instead.

Your test assembly needs a reference to Understudy: select its assembly definition, add Understudy under Assembly Definition References in the Inspector, then select Apply. The code you test must be in an assembly definition that the test assembly references, as the Test Framework requires. For more information, refer to Set up a test assembly.

Step 1: Stub a member

This method reads the frame time, so a test can't predict its result:

using UnityEngine;

public static class Movement
{
    public static float Step(float speed)
    {
        return speed * Time.deltaTime;
    }
}

Stub Time.deltaTime in the test, and Movement stays as it is:

using NUnit.Framework;
using Understudy;
using UnityEngine;

public class MovementTests
{
    [Test]
    public void StepMovesBySpeedTimesFrameTime()
    {
        Stub.Property(() => Time.deltaTime).Returns(0.5f);

        float distance = Movement.Step(2f);

        Assert.That(distance, Is.EqualTo(1f));
    }
}

Every read of Time.deltaTime in the code under test returns 0.5 until the test ends. The lambda, called a selection, names the member as the code under test reaches it, and everything it doesn't name runs for real. No interface, wrapper or injected clock is needed, and a read in the test itself still gets the real value.

The same works for Random.Range, Physics.Raycast, your own singletons, constructors, fields and events, with one entry point per kind of member: Stub.Method, Stub.Constructor, Stub.Field, and so on.

Step 2: Check what the code under test did

A stub also records what the code under test does with its member. This method saves a score only when it beats the best one:

using UnityEngine;

public static class HighScore
{
    public static void Submit(int score)
    {
        if (score > PlayerPrefs.GetInt("best"))
            PlayerPrefs.SetInt("best", score);
    }
}

The test sets the best score, replaces the save so it never writes to your real PlayerPrefs, and checks the recorded call:

using NUnit.Framework;
using Understudy;
using UnityEngine;

public class HighScoreTests
{
    [Test]
    public void SavesANewBestScore()
    {
        Stub.Method(() => PlayerPrefs.GetInt("best")).Returns(10);
        StubbedMethod saved = Stub.Method(() => PlayerPrefs.SetInt("best", Arg.Any<int>()));

        HighScore.Submit(25);

        Assert.That(saved.Calls, Has.Count.EqualTo(1));
        Assert.That(saved.Calls[0].Arguments[1], Is.EqualTo(25));
    }
}

Arg.Any<int>() matches any score, and Arguments[1] is the second argument of SetInt. To record calls and let the real member run, use Spy.Method instead of a stub.

Step 3: Read a leak warning

Delete the Stub.Property line from the first test and run it again. It fails, and the Console window shows a warning:

Leak in MovementTests.StepMovesBySpeedTimesFrameTime: Time.deltaTime ran for real at Movement.cs:7. Stub it, or declare it real with Real.

Understudy warns whenever a test reaches a clock, a random value or global state that it didn't declare, the usual causes of a test that passes on your machine and fails on another. Real declares a member that runs for real on purpose.

Next steps

For questions and bug reports, use the contact form or email justetools@gmail.com. I answer within one business day.