Writing Unit Tests

For unit testing you can use the classes from the haxe.unit package which are included in the default haxe installation.
There is also munit, a cross-platform haxe unit testing framework, that you can install through haxelib. The tutorial on this page is for haxe.unit. Unit Testing is simple. You create a new TestClass and add it to the MainClass. Then you create testMethods in your TestClass. Thats it. Now, if you compile and run the MainClass, all your tests should be executed.

Create new TestCase

Create a new class extending haxe.unit.TestCase and create your own test methods. Every test method name must start with test.

class TestFoo extends haxe.unit.TestCase {
    
    public function testBasic(){
        assertEquals( "A", "A" );
    }
    
}

Add new TestCase

Now you must have a main class in which you're adding your TestCase to a TestRunner.

class MyTest {
    
    static function main(){
        var r = new haxe.unit.TestRunner();
        r.add(new TestFoo());
        // your can add others TestCase here

        // finally, run the tests
        r.run();
    }
}

Compile & Execute

Save the classes in MyTest.hx. To compile the test create compile.hxml with the content:

-neko mytest.n 
-main MyTest

Now compile it on the commandline:

haxe compile.hxml

The new compiled file mytest.n can now be invoked on the commandline:

neko mytest.n

The result of the test:

Class: TestFoo .
OK 1 tests, 0 failed, 1 success

Test Functions

There are three functions you can use
Succeeds if a and b are equal, Where a is value tested and b is the expected value.

assertEquals(a, b)

Succeeds if a is true

assertTrue(a)

Succeeds if a is false

assertFalse(a)

Setup and Tear down


Some times you have the same code in multiple tests that setup the test or clean up after. You can overload the functions setup() and tearDown(). setup() is called before each test runs and tearDown is called once after all tests are run.
class TestFoo extends haxe.unit.TestCase {
    var str: String;

    override public function setup() {
        str = "foo";
    }

    public function testSetup() {
        assertEquals("foo", str);
    }
}

Comparing Complex Objects

With complex objects it can be difficult to generate expected values to compare to the actual ones. It can also be a problem that assertEquals doesn't do a deep comparison. One way around these issues is to use a string as the expected value and compare it to the actual value converted to a string using Std.string(). Below is a trivial example using an array.

public function testArray()
{
  var actual = [1,2,3];
  assertEquals("[1, 2, 3]", Std.string(actual));
}

Ready

From here on you are able to write your own unit tests. Some test are available on subversion : https://svn.motion-twin.com/haxeUnit

version #15807, modified 2012-12-22 03:58:53 by johnfn