Unit Testing Classes from Other Assemblies with Unity’s Test Framework in Unity 2022

GameDev Dustin
4 min readAug 31, 2023

--

In this article we’ll move onto some more real-world applications for Unity’s Test Framework package.

It’s nice to test bits of code within the Testing folder, but we’ll spend most of our time testing projects with complex existing code bases.

If you’re just diving into the Unity Test Framework for the first time, I recommend reading the QuickStart Guide first:

You may also want to check out “Creating a Play Mode Test with Unity’s Test Framework” here:

The PlayTest_NPC_Controller Class Project Location
We’ll be running the PlayTest_NPC_Controller class’ unit test methods.

Note its location in the project hierarchy above.

It is in the UTF-PlayTests folder.

The NPCController Class Project Location
We can see that the NPCController class we will be unit testing is not in our normal unit testing folders.

For us to access the NPCController class from our unit test class, we have to take into account that the NPCController class is from a folder location outside of the UTF-PlayTests folder.

We’ll need to add an Assembly Definition Reference for our unit testing class to “see” the NPCController class.

Our PlayTest_NPC_Controller class that contains our unit tests will be accessing the NPCController class which belongs to the Game Assembly Definition (asmdef) file.

As such, we have to add an Assembly Definition Reference to the asmdef that PlayTest_NPC_Controller belongs to.

The PlayTest_NPC_Controller belongs to the UTF-PlayTests asmdef in the UTF-PlayTests folder.

The NPCController Class
Now that we have set our unit testing asmdef file to “see” the gameplay asmdef, let’s take a look at the class we’ll be unit testing.

There are just a few basic methods in here.

We can setup a unit test for each of them, but I’ll just being unit testing the MoveNPCTowards() and TeleportNPC() methods.

Create the PlayTest_NPC_Controller Class
If you haven’t already, right click in the UTF-PlayTests folder and go to Create > Testing > C# Test Script.

Above we can see the general Arrange, Act, Assert pattern in use for two separate Unit Tests that will run in Play mode.

First, each method loads the scene that needs to be tested.

In this scene, I have an “NPC_Manager” gameobject with the NPCController class attached as a component.

I’ve assigned a simple sphere gameobject prefab called “NPC_Default”.

Each unit test method will get this gameobject by searching for the tag “NPC_Manager” and then grab the NPCController class attached.

From there, we can run any public method on the NPCController class.

Using the NPCController class, we’ll simply instantiate the NPC_Default prefab, move it, and then verify that it moved.

Run the Unit Tests
And as we can see above, both unit tests run and complete successfully.

Excellent!

--

--