zero's a life

An extra chance.

Mocking GameObjects in Unity Unit Tests

| Comments

A while back, I wrote a post about unit testing in Unity. In this post, I’ll go through a useful pattern to mock GameObjects in unit tests.

Make a GameObject

We can create a GameObject inside a test just like we would normally inside a Unity script.

GameObject testGo = new GameObject("test");

Passing a string to the GameObject constructor gives the GameObject that name.

We can even Instantiate prefabs

Since our test is not inheriting MonoBehaviour, we’ll have to call the Instantiate function directly, using the fully qualified namespace.

Remember that prefabs are just stored GameObjects, so we can use the testGo created above as our prefab.

GameObject go = UnityEngine.Object.Instantiate(testGo,
                                               Quaternion.identity) as GameObject;

Clean up

We can create GameObjects, but repeatedly running the test leaves our project cluttered up with old objects. We want our tests to clean up all mocked objects after running. We’ll do that using by using the fully qualified DestroyImmediate function.

We need to call DestroyImmediate instead of Destroy because the unit tests are running in the editor and delayed destruction won’t be invoked.


Mocking is easy

Following this pattern will give you the ability to mock objects to your hearts’ delight as you unit test your Unity code. As, always let me know if you have questions, comments, or concerns below or on twitter.