As part of my evaluation of FlexUnit and ASUnit for continuous integration, one of the rquirements is the ability to have an asynchronous test setup. Lets say you have a class under test that requires some XML in its constructor, and ideally you want to load that XML from an external source. While this doesnt work straight out of the box for flex unit, I found a very simple way to do this. Basically, Flexunit runs its TestCases by executingthe setUp method, then runMiddle() which runs the normal test method or the next asyncronous test. So the trick here is to get runMiddle to execute only when we are ready for it. This question had come up on the Flexcoders mailing list before, and Matt Chotin suggested a possible solution. Here’s mine:
Basically, what you can do is override the runMiddle function to be an empty method, and then when you are ready to actually run your test—in my example here its when an XML file has loaded—simply call super.runMiddle()
override public function setUp():void{ var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, completeHandler); var request:URLRequest = new URLRequest("employee.xml"); loader.load(request); } private function completeHandler(event:Event):void { var loader:URLLoader = URLLoader(event.target); instance = new AsyncSetupTestClass(new XML(loader.data)); super.runMiddle(); } override public function runMiddle():void{}
In my simple tests so far this seems to work, but if anyone notices anything out of whack, let me know…
Hi Paul!
Thanks for your documentation on the FlexUnit “stuff”. I was trying to verify the async test setup and ran into some problems. It turns out that although this successfully makes the runMiddle() run after any test setup, it doesn’t stop the listener from believing that the event succeeded.
Here’s some code that shows what I mean:
Obviously, the ‘testShouldFail’ test should fail, but the listener shows that it succeeded, even though it generates a traceback after the test results have been displayed.
Please let me know if there is anything that I can do to help figure this out….
Thanks.
–Kaleb
Hi Kaleb – I guess I should have reposted on this, but I’ve been in the middle of a project, so just haven’t had a chance to…
I too found the same problem as you. So what I ended up doing was writing a helper function for a test case that needs external data. It is passed a callback function so that once the data is loaded, the callback is triggered which does all the asserts. its probably easier to look at the code than to read my ramblings, so here goes:
So then when you want to run a test that needs this data, you would do it like this:
Hope this makes sense?
thx
PBH