Tile Map XML Tutorial NUnit Testing



Now that we have our tmx file being loaded by the xml serializer it is now time to test the data that was loaded in. For the testing we will be using Unity’s built in testing feature, which uses NUnit.Framework.  For more information please see http://docs.unity3d.com/Manual/testing-editortestsrunner.html
From Unity answers http://answers.unity3d.com/questions/1191898/which-version-of-nunit-ships-with-unity-cant-find.html
"The Editor Tests Runner is an implementation of the open source NUnit library - a well-known unit testing library for .Net languages. More information about NUnit can be found on http://www.nunit.org/. The implementaion is based on version 2.6.4."  
Create a new Editor Test C# Script in Scripts->Editor called TMXTest.

TMXTest.cs
using TileMapXML;
using NUnit.Framework;

public class TMXTest
{
    const string TMX_FILE_PATH = @"Assets/TileMapXML/Maps/Map002_xml.tmx";

    TMX tmx;

    [SetUp]
    public void Init()
    {
        tmx = new TMX();
        tmx.Load(TMX_FILE_PATH);
    }//void Init()

    [Test]
    public void TMXIsNotNull()
    {
        Assert.IsNotNull(tmx, "Failed to load tmx file, " + TMX_FILE_PATH);
    }//void TMXIsNotNull()

    [Test]
    public void TMXMapIsNotNull()
    {
        Assert.IsNotNull(tmx.map, "Failed to load map from " + TMX_FILE_PATH);
    }//void MapIsNotNull
}//public class TMXTest
TMX_File_PATH is going to be the path to your Tiled map file that you created earlier, to get this in Unity select the map that you created earlier and look in the console, you should see a message printed by our TMXFileInspector’s OnInspectorGUI method.

Notice that there is a method called Init that has [SetUp] attribute/tag, this will be run before every test that is run. This ensures that we have a clean setup for each test. In this method we are calling tmx.Load passing in the file to load which is what is stored in the const variable TMX_File_PATH.
There are 2 other Methods with the [Test] tag. These are the actual test that will be run. These 2 test verify that our tmx file did in fact load. In TMXIsNotNull method we are asserting that the tmx variable is not null by using Assert.IsNotNull. This just states that the tmx variable should have been created. In TMXMapIsNotNull method we verify that the map did load. If it failed to load the tmx.map variable would be null.
Now let’s run our test and make sure that everything passes. In Unity on the menu bar select Window->Editor Tests Runner

This should bring up the editor test runner window. Now if you select run all test this will run all of the editor test that we have created. You will get a dialog window telling you that your scene needs to be saved. You can choose to save your scene or cancel. We have nothing in our scene that needs to be saved, I choose cancel.
If everything is set up properly you should see green check marks next to all of the tests.

No comments:

Post a Comment