对整个脚本的执行进行超时检测
您是否遇到过一上班发现夜里进行的自动化回归测试因为某个 RFT 脚本 freeze 了,使得剩余的其他脚本没有执行?导致这种情况发生的原因通常是 RFT 脚本调用远程方法的时候,AUT 死锁了使得远程方法无法返回。只要将 AUT 进程杀掉就可以让脚本继续运行。如果脚本能够设置一个超时时间就可以防止这类问题发生,然而 RFT 本身并不支持这个功能。不过通过几行代码就可以轻松实现这个功能。
我们将超时检测封装到 Helper Superclass 中,如代码清单 6 所示。测试脚本再初始化的时候会开启一个 Timer, 当脚本运行时间超出设定值后,onTimeout 方法就被调用,同时脚本的执行被终止。
清单 6.
/** * 支持 timeout 的 Helper Superclass */ public class TestScriptHelper extends RationalTestScript { private static Timer timer = new Timer(true);
private static TimerTask timerTask = null; private long timeout = 0; /** * 设置脚本最长运行时间,单位为秒。* @param timeout 如果 timeout <= 0,脚本将不做超时检测 */ public void setTimeout(long timeout) { this.timeout = timeout; } public void onInitialize() { if (timeout > 0) { if (timerTask != null) timerTask.cancel(); timerTask = new TimerTask(){ public void run() { onTimeout(); // 终止脚本的运行 TestContext.getRunningTestContext().setAbort("Timeout"); } }; timer.schedule(timerTask, 1000 * timeout); } } public void onTerminate() { if (timerTask != null) { timerTask.cancel(); timerTask = null; } } /** * 子类可以通过覆盖该方法来做超时的清理工作 . */ public void onTimeout() { } } |
代码清单 7 中显示如何在测试脚本中使用超时检测。注意 DemoScript 的 Helper Superclass 为 TestScriptHelper,要在脚本的构造方法中通过 setTimeout 方法来指定超时时长。
清单 7.
package testcases; import resources.testcases.DemoScriptHelper;
public class DemoScript extends DemoScriptHelper {
public DemoScript() { setTimeout(3); } public void onTimeout() { System.out.println("DemoScript runs out of time!"); //TODO 清理工作,比如 kill 被测程序,删除用户数据等 } public void testMain(Object[] args) { sleep(20); //TODO 实现测试步骤 } } |