uUnit: Configuring MonoBehavior property with prefab

I just started using uUnit from Codelogic Ltd. and the documentation falls a bit short. I want to test a MonoBehavior (called “GameBoard”) which exposes a public class variable of type GameObject (called “tile”). Normally this variable would be configured with a prefab using the Inspector panel in the Unity editor, but I’m not sure a) how to reference a prefab from a uUnit test, and b) how to configure the GameBoard.tile variable from within the uUnit test.

I can successfully use uUnit’s GameObjectHost to establish the GameBoard behavior instance, but from there I don’t know what to do. Here’s a simplified version of my test class.

using UnityEngine;
using uUnit;

[TestFixture]
public class GameBoard
{

    [Test]
    public void NewGameShouldStartWithNineTiles()
    {
        GameBoard gameBoard = GameObjectHost.HostScript<GameBoard>();

        // Set gameBoard.tile here somehow??

        gameBoard.SetupNewGame();

        Assert.AreEqual(9, gameBoard.TileCount, "Should start with 9 tiles.");
    }
}

1 Answer

1

I figured out a solution. I don’t know for sure it’s the best one, but it seems reasonable.

I should mention one additional aspect of my sample scenario that I previously left out. The “tile” property is referenced in my behavior’s Start() method which adds a bit of complexity to how the test must be written. Now, onto my solution…

To start, in the scene that I’ve set up for running uUnit I’ve dragged an instance of my “Tile” prefab. With that in place, I’m able to use the following pattern for my test. Note the use of yield return null and the test method return type of IEnumerator which both turn out to be critical for this to work.

using UnityEngine;
using System.Collections;
using uUnit;
 
[TestFixture]
public class GameBoard
{
 
    [Test]
    public IEnumerator NewGameShouldStartWithNineTiles()
    {
        GameBoard gameBoard = GameObjectHost.HostScript<GameBoard>();
        gameBoard.tile = GameObject.Find("Tile");

        // Wait a frame so the behavior life cycle methods (e.g. Start()) are run before continuing.
        yield return null;

        gameBoard.SetupNewGame();

        Assert.AreEqual(9, gameBoard.TileCount, "Should start with 9 tiles.");
    }
}