Automated Tests in Unity
I ran into a few issues trying to get unit tests running in the Unity engine. The setup isn’t hard but getting there just takes a bit of patience.
Open the test runner
Go to Window > General > Test Runner. This is the main area for running tests.
Create a test script
Click the “Create Test Script in current folder” button in the Test Runner. This does two things:
- It creates an assembly definition file. This is important for keeping the test dependencies separate from your production code.
- It creates a test script. You can rename it to whatever makes sense for what you’re testing.
Fixing the “Missing Assembly Reference” error
Your tests won’t be able to see your actual game scripts until you wire up the manual assembly references (separate from the first step). The goal is to have the test assembly reference the real code assembly.
- Go to your scripts folder (likely Assets/Scripts) and right-click -> Create Assembly Definition. This creates an assembly definition file for the real code.
- Then go back to your tests assembly definition in Unity and add a reference to the real assembly you just created.
Edit mode tests vs play mode tests
You’ll need to decide upfront whether each test is Edit Mode or Play Mode, and make sure your assembly config reflects that.
Edit mode
This type of test runs when you’re editing scenes, assets, or running the Unity Editor normally (not part of a running game/Play mode). Basically there are no game physics, time progression, or player input simulation.
Play mode
This test runs when you press the Play button in the Unity Editor, or when the game is built and running. Your test cases can validate physics updates, coroutines run, Update()/FixedUpdate() execute, time passes, etc.
Run the tests
Select your test in the Test Runner and hit “Run Selected.” You’ll see a pass or fail result directly within the window.