8/10/2006

 

Async Unit Tesing in ActionScript3

This is a cutting-edge topic, if you are not interested in programming in next generation flash application, please ignore me:) The most mature unit testing tool available in ActionScript3/Flex2 world is FlexUnit2, which is a oss project hosted at labs.adobe.com. It is a simulation of JUnit, from framework design to usage. Nothing changed, except Thread.sleep is missing in Flash world. If we can not wait for a few seconds, how to test async behavior? To solve this problem, FlexUnit introduce a method in class TestCase, called "addAsync". It takes minimal two parameters. You can use it like this:
  loader.addEventListener(Event.COMPLETE, addAsync(onIndexPageLoaded, 1000));
The value returned by addAsync is a function wrapping your event handler. To look up full documentation about this method, see here. After adding a "Async", FlexUnit will wait for few seconds to finish testing one test method. But here are some findings and tips for you:
  1. FlexUnit is using "Timer" to wait for finishing. It will not pause execution actually, but will check for the result later. i.e:
      loader = new URLLoader();
      loader.addEventListener(Event.COMPLETE, addAsync(onIndexPageLoaded, 1000));
      loader.load(new URLRequest("twspike-index.html"));
      doSomething();
    
    doSomething will be executed immediately after loader.load(...).
  2. You can not use "addAsync" in setUp. Because setUp and testXXX is two different test cases, so FlexUnit will wait for setUp to finish instead of waiting for your actual testing code to finish. Currently, the error reported is quite mistery.
  3. How to actually wait for something happened than start testing? Here is the home made HOW-TO:
    private function onIndexPageLoaded(event:Event):void {
      parser = new IndexPageParser(loader.data);
      checker.call(this);
    }
    private function check(checker:Function):void {
      this.checker = checker;
      loader = new URLLoader();
      loader.addEventListener(Event.COMPLETE, addAsync(onIndexPageLoaded, 1000));
      loader.load(new URLRequest("twspike-index.html"));
    }
    public function blog_data_should_not_be_null():void {
      check(function():void {
        assertNotNull(parser.blogData);
      });
    }
    public function blog_data_should_be_valid_xml():void {
      check(function():void {
        XML(parser.blogData);
      });
    }
    
To summary it up: Wrapping your testing code in a function, Passing it to a check method, saving the testing code and start to execute the async action. In the event handler, call the saved testing code. It is annoying, I know...

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]