Introduction To Unity Unit Testing

Learn all about how Unit Tests in Unity work and how to use them in your projects in this great tutorial. By Anthony Uccello.

Leave a rating/review
Download materials
Save for later
Share

Curious how unit testing works in Unity? Unfamiliar with how unit testing works in general? If you answered yes to these questions then this tutorial is for you. In this tutorial you’ll learn the following about unit testing:

  • What it is
  • The value it offers
  • Pros and cons
  • How it works in Unity using the Test Runner
  • Writing and running unit tests that pass
Note: This tutorial assumes you are familiar with C# and basic Unity development. If you are new to Unity, check out our other Unity tutorials.

What Is a Unit Test?

Before diving into code, it’s important to have a solid understanding of what unit testing is. Put simply, a unit test is…a unit test. :]

A unit test is (ideally) for testing a single “unit” of code. Exactly what makes up a “unit” varies, but the important thing to keep in mind is that a unit test should be testing exactly one ‘thing’ at a time.

You should design a unit test to validate that a small, logical, snippet of code performs exactly as you expect it to in a specific scenario. This might be hard to grasp before you’ve written any unit tests, so consider this example:

You’ve written a method that allows the user to input a name. You wrote the method so there are no numbers allowed in the name, and the name can only be ten characters or less. Your method intercepts each keystroke and adds that character to the name field as shown below:

public string name = ""
public void UpdateNameWithCharacter(char: character)
{
    // 1
    if (!Char.IsLetter(char))
    {
        return;
    }

    // 2
    if (name.Length > 10)
    {
        return;
    }

    // 3
    name += character;
}

This is what’s going on here:

  1. If the character is not a letter, this code exits the function early and doesn’t add the character to the string.
  2. If the length of the name is ten characters or greater, it prevents the user from adding another character.
  3. Once those two tests pass, the code adds the character to the end of the name.

This method is testable because it does a “unit” of work. Unit tests enforce the method’s logic.

Looking at Example Unit Tests

How would you write unit tests for the UpdateNameWithCharacter method?

Before you get started with implementing these unit tests, you’ll need to think carefully about what the tests are doing, and come up with names for them.

Take a look at the sample test method names below. The names should make it clear what’s being tested:

UpdateNameDoesntAllowCharacterAddingToNameIfNameIsTenOrMoreCharactersInLength

UpdateNameAllowsLettersToBeAddedToName

UpdateNameDoesntAllowNonLettersToBeAddedToName

From these test method names, you can see that you’re testing that the “unit” of work being performed by UpdateNameWithCharacter is doing what it should. These test names might seem long and very specific, but this is helpful.

Every unit test you write makes up part of a test suite. A test suite houses all unit tests related to a logical grouping of functionality (like your combat unit tests). If any individual test in a test suite fails, the entire test suite fails.

unit testing: test suite

Starting Up the Game

Open the Crashteroids Starter project (you can find the Download Materials button at the top or bottom of this tutorial), and open the Game scene in Assets / RW / Scenes.

unit testing: game one

Click Play to get Crashteroids started, and then click the Start Game button. Use the left and right arrow keys to move the spaceship left and right.

Press the spacebar to fire a laser. If a laser hits an asteroid, the score will go up by one. If an asteroid hits the ship, the ship explodes and it’s game over (with the option to start again).

unit testing: game two

Try playing for a while, and then make sure the ship gets hit by an asteroid to see that Game Over triggers.

unit testing: game three

Getting Started with the Unity Test Runner

Now that you know how the game works, it’s time to write unit tests to ensure everything behaves as it should. This way if you (or anyone else) decides to update the game, you can be confident in knowing that the update didn’t break anything that was working before.

To write tests, you first need to know about Unity’s Test Runner. The Test Runner lets you run tests and see if they pass. To open the Unity Test Runner, choose Window ▸ General ▸ Test Runner.

After the Test Runner opens as a new window, you can make life easier by clicking the Test Runner window and dragging it next to your Scene window.

Setting Up NUnit and Test Folders

Test Runner is the unit testing feature provided by Unity — but it utilizes the NUnit framework. As you get more serious about writing unit tests, you should consider reading the wiki on NUnit to learn more. For now, everything you need to know will be covered here.

In order to run tests, you first need to create a test folder to hold your test classes.

In the Project window, select the RW folder. Look at the Test Runner window and make sure PlayMode is selected.

Click the button which says Create PlayMode Test Assembly Folder. You will see a new folder appear just under the RW folder. The default name Tests is fine, so you can press Enter to finalize the name.

create tests folder

You might be curious what the two different tabs inside the Test Runner are.

The PlayMode tab is for tests that will run while in Play mode (as if you were playing the game in real time). The EditMode tests will run outside of Play mode, which is great for testing things like custom Inspector behaviors.

For this tutorial, you’ll focus on PlayMode tests. But feel free to experiment with EditMode testing once you feel ready. Make sure the PlayMode tab is selected from now on when dealing with the Test Runner window.

What’s in a Test Suite?

As you learned above, a unit test is a function that tests the behavior of a small, specific, set of code. Since a unit test is a method, it needs to be in a class file in order to run.

The Test Runner will go through all your test class files and run the unit tests in them. A class file that holds unit tests is called a test suite.

A test suite is where you logically divide your tests. You want to divide your test code among different, logical suites (e.g. a test suite for physics and a separate one for combat). For this tutorial, you only need one test suite, so it’s about time you created it. :]