OK, you install AsUnit, you follow the Quickstart Directions, and you grab Test Driven Development: By Example or some other book or online reference and start converting Java to AS2.
The first thing that’s going to stick in your craw is when you try to use assertEquals(). You’re going to get an error about using the incorrect type or something along those lines. This is because in AsUnit, assertEquals requires two arguments that are Comparable. Note the capital C. Comparable is an interface: com.asunit.utils.Comparable. (You can find all the AsUnit classes in the Classes directory of your Flash Configuration directory.) Comparable specifies two methods: equals() and toString(). I really don’t like the way that assertEquals is implemented. First of all it forces a tight coupling between your testing environment and your project code. If you make a class that you might want to test a member of for equality, you have to make it implement com.asunit.utils.Comparable. Furthermore, you can’t use it to test primitive values at all. So it’s impossible to do something like:
assertEquals(100, myPay.amount);
because 100 is a primitive constant and can’t implement an interface, and even if myPay’s class implemented Comparable, its amount property most likely wouldn’t.
The reason it is implemented this way is so that you can compare higher level objects. Any two objects will report false to obj1 == obj2, even if everything about them is exacty the same. The Comparable interface forces you to write an equals method that compares an instance of your class with another instance and reports true or false. That’s nice, but it breaks too many other tests which should be valid. So I re-wrote assertEquals to the following:
public static function assertEquals(msg:Object, assertion1, assertion2):Void {
if(arguments.length == 2) {
assertion2 = assertion1;
assertion1 = msg;
msg = "";
}
if(assertion1.equals != undefined)
{
addTestResult(String(msg), "assertEquals", assertion1.equals(assertion2));
}
else if(assertion2.equals != undefined)
{
addTestResult(String(msg), "assertEquals", assertion2.equals(assertion1));
}
else
{
addTestResult(String(msg), "assertEquals", assertion1 == assertion2);
}
}
You can find this assertEquals in com/asunit/Assert.as in the Classes directory. Just comment it out and replace it with this. My logic is: if either one of the objects implements an equals function, use it. If neither does, do a straight == comparison. This decouples the testing and project code, and allows testing of virtually any type. If you see any enhancements or improvements that could be made, feel free to post them. This one works great for me, but I’m not saying it couldn’t be better.