flex和后台打交道几乎都是异步方式的,我最近就在team里面负责service层(一些mvc框架里称作proxy层)的编码工作,撇开传统的Alert,Trace等调试方式,决定引入正规的单元测试flexunit,但是对于异步操作来说,单元测试并非十分简单,网上找了些英文资料,实践后整理一份教材供大家参考
关于flexunit的一些基础知识可以参考我的上一篇文章”利用flexunit进行单元测试一(同步测试)“。
首先看一下我们的service类,这里为了便于演示代码使用HttpService方式
首先建一个xml作为访问资源
<domain>
<ip>
192.168.1.100</ip>
</domain>随后建立一个方法使用httpService来访问这个xml资源
public
class
MyService
{
private
var
getDomainRetFun:
Function
;
public
function
getDomain(
retFun:
Function
)
:
void
{
getDomainRetFun = retFun;
var
service:
HTTPService = new
HTTPService(
)
;
service.url
= "assets/domain.xml"
;
service.addEventListener
(
ResultEvent.RESULT,getDomainHandler)
;
service.send
(
)
;
}
private
function
getDomainHandler(
evt:
ResultEvent)
:
void
{
if
(
evt.result!
=null
)
{
var
ip:
String
= evt.result.domain
.ip
getDomainRetFun(
ip)
;
}
else
{
getDomainRetFun(
"error"
)
;
}
}
}接下来写testCase,我们可以看到这里使用了一个timer来延迟断言执行的时间。这里设置延迟3000毫秒,addAsync()函数是由父类TestCase实现,设置的是3秒延迟过后需要执行的函数 第一个参数为 需要执行断言的 回调函数名 ,第二个参数是timeout,第三个为传递给回调函数的参数,我们这里就设置前2个即可
public
class
MyServiceTest extends TestCase
{
private
var
timer
:
Timer
;
private
var
myService:
MyService;
public
function
MyServiceTest(
methodName:
String
=null
)
{
super
(
methodName)
;
}
override public
function
setUp(
)
:
void
{
timer
= new
Timer
(
3000
, 1
)
;
myService = new
MyService(
)
;
super
.setUp(
)
;
}
override public
function
tearDown(
)
:
void
{
timer
.stop
(
)
;
timer
= null
;
myService = null
;
super
.tearDown(
)
;
}
//设置一个临时变量来存放回调函数返回结果,以用于断言时候的比较
private
var
tmp:
String
= ""
;
public
function
testGetDomain(
)
:
void
{
timer
.addEventListener
(
TimerEvent
.TIMER_COMPLETE
,addAsync(
handleTimerComplete,5000
)
)
;
timer
.start
(
)
;
myService.getDomain(
getDomainCompelet)
;
}
private
function
getDomainCompelet(
ip:
String
)
:
void
{
tmp = ip;
}
private
function
handleTimerComplete(
evt:
TimerEvent
)
:
void
{
Assert.assertEquals(
"192.168.1.100"
,tmp)
;
}
}ui方面加入suite后就就可以run test了
如果有错误则会提示
flexunit来测试异步或者测试事件还是有些繁琐的。有些时候还不如Alert来的简单明了,这一点上大家仁者见仁智者见智了。
ui开发方面的测试还是以视觉为准吧,至于那些看不见效果的service层或者util类上,使用flexunit来进行单元测试还是十分有必要的。
原文转自:http://blog.chinaunix.net/uid-366408-id-116441.html