I’ve used http://nunit.org extensively for Unit Testing C# apps, however it’s not compatible with Unity.
I ran across a Unity forum post for UUnit http://forum.unity3d.com/viewtopic.php?t=6515&highlight=uunit, however it was written in BOO script.
I adapted part of the NUnit source code to work with Unity (as a C# script) and attached an example project that shows all the same attributes work.
A typical test class looks similar to the following.
using System;
[TestFixture]
public class MyTestClass
{
[TestFixtureSetUpAttribute]
public void MyTestFixtureSetUpAttribute()
{
TestRunner.ReportLog("Call setup once before all [Test] and [SetUp]");
}
[SetUp]
public void MySetUp()
{
TestRunner.ReportLog("Call setup before each [Test]");
}
[Test]
public void MyGoodTest()
{
TestRunner.ReportLog("Do a good test");
}
[Test]
public void MyBadTest()
{
TestRunner.ReportLog("Do a bad test");
throw new System.Exception("I did a bad thing");
}
[TearDown]
public void MyTearDown()
{
TestRunner.ReportLog("Call after each [Test]");
}
[TestFixtureTearDown]
public void MyTestFixtureTearDown()
{
TestRunner.ReportLog("Call setup once after all [Test] and [TearDown]");
}
}
To run these tests, you don’t need to instantiate anything. Simply run
TestRunner.Execute();
Using reflection, any class that you’ve added [TestFixture] will be found.
I used the same attributes that you’d be familar with if you’ve used Visual Studio or NUnit for unit testing.
There’s an button in the example that runs the unit tests.
Output is written to the console output.
If you aren’t already familar with NUnit, take a look at their site and read the documentation.
Only use [TestFixture] on public classes that have a valid constructor. I say this because you might try to use [TestFixture] on a MonoBehaviour script, so don’t do that. Instead create a new test class and use a public reference to your MonoBehavior script. If you need to, you could get away with using a ScriptableObject.
I didn’t port the Asserts from NUnit.
Assert.Fail(); Assert.AreEqual();
Instead if a [Test] method should throw a System.Exception, the test failed. If an exception wasn’t thrown it will pass.
The test results for a run would look like the following:
[TestRunner] **** Summary ****
[PASS] MyTestClass.MyTestFixtureSetUpAttribute
[PASS] MyTestClass.MySetUp
[PASS] MyTestClass.MyGoodTest
[PASS] MyTestClass.MyTearDown
[PASS] MyTestClass.MySetUp
[FAIL] MyTestClass.MyBadTest
[PASS] MyTestClass.MyTearDown
[PASS] MyTestClass.MyTestFixtureTearDown
To use:
import the package NUUnit.unitypackage
Open:
Tests\TheScene
129846–4830–$nuunitunitypackage_100.zip (19.6 KB)