使用ASUnit单元测试框架测试ActionScript代码
ASUnit是使用纯Flash应用程序进行测试驱动开发的首选工具。它是开源的单元测试框架,可用于ActionScript2.0、3.0。
ASUnit2.x完全和Flash IDE集成,支持Mozilla的XUL UI。此框架运行开发者轻松创建和管理类、测试用例、测试集,并浏览特定的测试结果。
本文解释了怎样使用ASUnit框架建立ActionScript单元测试。
1)创建名为AsUnitExample的目录
下载ASUnit框架的zip文件,地址为:http://sourceforge.net/project/showfiles.php?group_id=108947&package_id=208528
复制ActionScript3目录的内容到AsUnitExample目录。本文以AsUnitExample目录为项目根目录。且AsUnitExample目录应包含文件AsUnitTestRunner.as和asunit目录、mx目录。
2)打开并检查AsUnitExample/AsUnitTestRunner.as
复制下面的源代码:
- package{
- importasunit.textui.TestRunner;
- publicclassAsUnitTestRunnerextendsTestRunner{
- publicfunctionAsUnitTestRunner(){
- start(AllTests,null,TestRunner.SHOW_TRACE);
- }
- }
- }
3)创建一个.fla文件服务于测试容器
在Flash IDE,从菜单File->New->Flash File(ActionScript3),建立一个新的Flash文件,保存文件为AsUnitExample/AsUnitTestRunner.fla。在属性窗口,设置文件类属性为AsUnitTestRunner。保存它。
4)创建一简单的类,并运行测试
粘贴下列源码到AsUnitExample/Example.as文件。
- package{
- publicclassExample{
- publicfunctionadd(num1:Number,num2:Number):Number{
- returnnum1+num2;
- }
- }
- }
5)为例子类创建一个测试
在Flash IDE,从菜单File->New->ActionScript File,新建一AS文件,另存文件为AsUnitExample/ExampleTest.as。粘贴下列代码:
- package{
- importasunit.framework.TestCase;
- publicclassExampleTestextendsTestCase{
- privatevar_instance:Example;
- /**
- *Constructor
- *
- *@paramtestMethodNameofthemethodtotest
- */
- publicfunctionExampleTest(testMethod:String){
- super(testMethod);
- }
- /**
- *Preparefortest,createinstanceofclassthatwearetesting.
- *InvokedbyTestCase.runMethodfunction.
- */
- protectedoverridefunctionsetUp():void{
- _instance=newExample();
- }
- /**
- *Cleanupaftertest,deleteinstanceofclassthatweweretesting.
- */
- protectedoverridefunctiontearDown():void{
- _instance=null;
- }
- /**
- *Testofwhetherornotclassproperlyinstantiated
- */
- publicfunctiontestInstantiated():void{
- assertTrue("Exampleinstantiated",_instanceisExample);
- }
- /**
- *Testthatisborntolose.
- */
- publicfunctiontestFail():void{
- assertFalse("failingtest",true);
- }
- /**
- *Testtheadditionmethodonexample
- */
- publicfunctiontestAddition():void{
- varresult:Number=_instance.add(2,3);
- assertEquals("Expected:5Received:"+result,result,5);
- }
- }
- }
6)创建测试集
在Flash IDE,从菜单File->New->ActionScript File,新建一AS文件,另存文件为AsUnitExample/AllTests.as。粘贴下列代码:
- package{
- importasunit.framework.TestSuite;
- publicclassAllTestsextendsTestSuite{
- publicfunctionAllTests(){
- super();
- addTest(newExampleTest("testInstantiated"));
- addTest(newExampleTest("testAddition"));
- }
- }
- }
7)在Flash IDE,编译AsUnitTestRunner.fla(通过运行Control->Test Movie)。