在Flash和Flex中使用asunit
转http://www.colorhook.com/blog/?p=346
asunit是一个开源的Flash ActionsScript测试框架。这里有一些关于它的参考资料:
- AsDoc Reference
- Getting Started with AsUnit and Flash Authoring CS3
- Getting Started with AsUnit and FlashDevelop
- Flex MXML Projects in AsUnit
- Developing Visual Components with AsUnit
使用asunit可以遵循以下几个步骤:
- 编写TestCase
- 编写TestSuite
- 编写TestRunner
MyClass是需要被测试的类,根据以上步骤来对它进行单元测试。
package{ public class MyClass{ public function doAdd(n1:Number,n2:Number):Number{ return n1+n2; } public function doSub(n1:Number,n2:Number):Number{ return n1-n2; } } }
1. 编写TestCase
package{ import asunit.framework.TestCase; public class MyClassTest extends TestCase{ private var instance:MyClass; public function MyClassTest(method:String){ super(method) } override protected function setUp():void{ instance=new MyClass; } override protected function tearDown():void{ instance=null; } public function testAdd():void{ assertTrue("Example add",instance.doAdd(1,2)==3); } public function testSub():void{ assertEquals(-1,instance.doSub(1,2)); } } }
2. 编写TestSuite
package{ import asunit.framework.TestSuite; public class AllTests extends TestSuite{ public function AllTests(){ super(); addTest(new MyClassTest("testAdd")); addTest(new MyClassTest("testSub")); } } }
3. 编写TestRunner
(1) 这个是用于Flash IDE中的TestRunner。
package{ import asunit.textui.TestRunner; public class TestRunnerExample extends TestRunner{ public function TestRunnerExample(){ super(); start(AllTests,null,TestRunner.SHOW_TRACE); } } }
(2) 这个是用于Flex Builder中的TestRunner。
<?xml version="1.0" encoding="utf-8"?> <runner:FlexRunner xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:runner="asunit.textui.*" layout="absolute" minWidth="1024" minHeight="768" creationComplete="initApp()"> <mx:Script> <![CDATA[ private function initApp():void{ this.start(AllTests,null,false); } ]]> </mx:Script> </runner:FlexRunner>
4. 运行结果
AsUnit 3.0 by Luke Bayes and Ali Mills Flash Player version: WIN 10,0,2,54 .. Time: 0.081 OK (2 tests) Time Summary: 63ms : MyClassTest 15ms : MyClassTest