- Define classes that inherit from
UnitTest - Within these classes, define functions with
Testin their names - Within these functions, call
Assert,AssertEqual, etc. - Attach the
TestRunnerscript to an object in your scene
When the object with the TestRunner behavior initializes, it will look for all subclasses of UnitTest, create an object with that behavior attached, and call all methods containing the string Test. It will count the assertions you make and print out friendly messages with stack traces if there are failures or errors.
classFooTestextendsUnitTest{functionTestThatWillPass(){Assert(true);}functionTestThatWillFail(){Assert(false);}functionTestThatWillError(){throw'a chicken';}functionTestWithACustomFailureMessage(){AssertUnequal(4,5,"There are four lights!");}functionTestArrayContentsButFail(){AssertContains(0,[1,2,3,4,5]);}functionTestThatCreatesObjects(){testObject=newGameObject();testObject.transform.position=Vector3(5,5,5);Assert(testObject.transform.position.z==5);Destroy(testObject);}functionMethodThatIsNotCalled(){// this method doesn't have 'Test' in its name, so who cares what happens here?}}or, in C#,
usingUnityEngine;publicclassFooTest:UnitTest{publicvoidTestA(){Assert(true,"this test succeeds");}publicvoidTestB(){Assert(false,"this test fails");}}And it should produce the following output in your Unity console:

Note that you'll need to place UnitTest.js and TestRunner.js in your Plugins folder or some other folder that gets compiled first, if you want to use this library with C# tests.
This isn't meant to be a comprehensive test framework, just a simple tool to make testing Unity code a little easier. It's probably best to avoid making assertions about objects that are actually part of the scene, and if you create any objects or add any components inside these tests, you should remove them manually afterwards.