24.5.在测试前后运行代码

24.5.1. 问题
我需要在每个测试用例测试前或测试后运行特定的代码。
24.5.2. 解决办法
重写TestCase类的setUp和tearDown方法。
24.5.3. 讨论
默认情况下,每个TestCase中的测试方法都会在自己的TestCase实例中运行。如果多个测试方法需要同一个系统状态或数据,你可以使用setUp方法统一进行设置而不用在每个测试开始前显式调用某个设置方法。同理,如果需要在每个测试后清理某个对象或测试断言,无论是否有断言失败或错误,tearDown方法必须被运行。请切记一旦有断言失败或产生错误,测试方法将会停止执行。tearDown方法还有点好处就是如果测试使用到外部资源或对象的话可以进行释放。

setUp方法很常用,比如用来保持当前正常状态数据到系统中。对于复杂的测试,可能需要挂接多个对象或连接到外部资源。如要在测试之前创建代码,像下面那样重写setUp方法:
+展开
-ActionScript
override public function setUp():void
{}

你可以在这里放置任何代码,包括断言。如果某些资源或对象不存在的话,在setUp方法里使用断言可直接快速取消测试。注意如果setUp方法内出现断言失败或抛出异常,预订的测试方法或tearDown方法都不会被调用。这是tearDown方法唯一不被调用的情况。

类似setUp,tearDown方法是在每个测试后运行,无论是否有失败断言或异常。可以把它理解成try...catch...finally块的finally部分。按这种理解,也就是说tearDown方法并不是必需的。

请记住默认下每个测试方法都是运行在自己的TestCase实例中,这就意味着类变量将被设置为实例值,取消之前测试方法所作的修改。常见的如tearDown方法包括执行每个测试方法运行后生成的贡献断言或对外部资源的释放,比如断开Socket。要在每个测试方法后面运行代码,像下面那样重写tearDown方法:
+展开
-ActionScript
override public function tearDown():void
{}

下面的代码演示每个测试方法何时运行,调用setUp,测试代码和tearDown方法:
+展开
-ActionScript
package
{
import flexunit.framework.TestCase;
public class SetUpTearDownTest extends TestCase
{
private var _phase:String = "instance";
override public function setUp():void
{
updatePhase("setUp()");
}
override public function tearDown():void
{
updatePhase("tearDown()");
}
public function testOne():void
{
updatePhase("testOne()");
}
public function testFail():void
{
updatePhase("testFail()");
fail("testFail() always fails");
}
public function testError():void
{
updatePhase("testError()");
this["badPropertyName"] = "newValue";
}
private function updatePhase(phase:String):void
{
trace("Running test", methodName, "old phase", _phase,
"new phase", phase);
_phase = phase;
}
}
}

输出信息如下:
Running test testFail old phase instance new phase setUp()
Running test testFail old phase setUp() new phase testFail()
Running test testFail old phase testFail() new phase tearDown()
Running test testError old phase instance new phase setUp()
Running test testError old phase setUp() new phase testError()
Running test testError old phase testError() new phase tearDown()
Running test testOne old phase instance new phase setUp()
Running test testOne old phase setUp() new phase testOne()
Running test testOne old phase testOne() new phase tearDown()

注意每个测试都以实例的_phase值开头,无论是否有断言失败或异常,setUp和tearDown 方法都被执行。

加支付宝好友偷能量挖...


评论(0)网络
阅读(94)喜欢(0)flash/flex/fcs/AIR