在 FlashDevelop4 中使用 ASUnit 单元测试框架

1. 下载 ASUnit 框架

到官网 http://www.asunit.org 下载框架源代码包。

 

2. 创建新项目

在 FlashDevelop 中创建一个新项目,具体方法参加 FlashDevelop 帮助手册。

 

3. 将 ASUnit 添加到项目中

在项目的属性面板中,切换到"Classpaths"选项,将 ASUnit 代码路径加入到项目的 classpaths 中,具体添加的应该是 ASUnit 代码包下的 as3\src 子目录。

添加 classpath 后 ASUnit 的代码将出现在项目树中:

 

4. 添加测试程序代码

首先为测试程序创建一个独立的一级子目录 tests(和src目录同级),与项目功能代码 src 隔离开更易于管理。在 tests 下创建子目录 src/test,test是包名,可以按个人喜好设置,比如与项目代码结构保持一致。

 

在 tests/src/test 目录下创建 AllTests.as 类文件,该类需要继承自 asunit.framework.TestSuite,需要执行的测试用例都在该类中添加,示例代码:

 1 package test {
 2   import asunit.framework.TestSuite;
 3   
 4   /**
 5    * ...
 6    * @author Edward
 7    */
 8   public class AllTests extends TestSuite {
 9     
10     public function AllTests() {
11       super();
12     }
13   
14   }
15 
16 }

 

再创建一个具体的测试用例代码文件,例如:TestFirstTry.as,该类需要继承自 asunit.framework.TestCase,示例代码:

 1 package test {
 2   import asunit.framework.TestCase;
 3   
 4   /**
 5    * ...
 6    * @author Edward
 7    */
 8   public class TestFirstTry extends TestCase {
 9     
10     public function TestFirstTry(testMethod:String = null) {
11       super(testMethod);
12     }
13     
14     public function testIntegerMath():void {
15       var i:int = 5;
16       assertEquals(5, i);
17       i += 4;
18       assertEquals(9, i);
19     }
20     
21     public function testFloatMath():void {
22       var i:Number = 5;
23       assertEqualsFloat(5, i, 0.001);
24       i += 4;
25       assertEqualsFloat(8, i, 0.001);
26     }
27   
28   }
29 
30 }

 

在 AllTests 中添加测试用例,在调用 TestSuite.addTest 方法时如果没有指定待测试的 TestCase 的某一具体方法名(TestCase 子类构造函数的参数),那么 TestCase 子类中所有方法名以 test 开头的都将被执行!这个特性很便于对功能模块进行整体测试。

1     public function AllTests() {
2       super();
3       addTest(new TestFirstTry());
4       //addTest(new TestFirstTry("TestIntegerMath"));
5       //addTest(new TestFirstTry("TestFloatMath"));
6     }

 

最后,在 Main.as 中添加单元测试启动代码:

 1 package {
 2   import flash.display.Sprite;
 3   import flash.events.Event;
 4   
 5   import asunit.textui.TestRunner;
 6   import test.AllTests;
 7   
 8   /**
 9    * ...
10    * @author Edward
11    */
12   public class Main extends Sprite {
13     
14     public function Main():void {
15       if (stage)
16         init();
17       else
18         addEventListener(Event.ADDED_TO_STAGE, init);
19     }
20     
21     private function init(e:Event = null):void {
22       removeEventListener(Event.ADDED_TO_STAGE, init);
23       
24       var unit_tests:TestRunner = new TestRunner();
25       stage.addChild(unit_tests);
26       unit_tests.start(AllTests, null, TestRunner.SHOW_TRACE);
27     }
28   
29   }
30 }

 

5. 执行单元测试

编译运行项目将看见下面的输出内容:

输出中显示有一个失败测试项,只要将 TestFirstTry.testFloatMath 方法中的 ‘8’ 改成 ‘9’ 就好了。

 

参考资料

 

posted @ 2013-01-08 16:13  edwardlost  阅读(415)  评论(0编辑  收藏  举报