在RFT中,异常处理的方式与QTP有所不同。QTP中的异常处理主要依赖VB Script的On Error Resume Next以及恢复场景(Recovery Scenario)的机制。
在RFT中,由于脚本继承于RationalTestScript,因此处理可以在脚本中使用JAVA的try-catch语句做一般的异常处理外,还可以重写IobjectManagerEventListener接口的各种事件,例如找到多个相同对象时的onAmbiguousRecognition事件、找不到对象时的onObjectNotFound事件等。
下面的脚本重写了onAmbiguousRecognition事件进行定制处理,testObjectMethodState对象的findObjectAgain方法让RFT再次查找对象。
public void onAmbiguousRecognition(ITestObjectMethodState testObjectMethodState,
TestObject[] choices,
int[] scores)
{
System.out.println("有"+choices.length+"个相同的对象!");
for(int i=1;i<choices.length;i++)
{
TopLevelSubitemTestObject window = (TopLevelSubitemTestObject)choices[i];
window.close();
}
// 再次查找对象
testObjectMethodState.findObjectAgain();
}
以下脚本重写了onObjectNotFound事件。(参考RFT的帮助文档Handling unexpected active window)
/**
* Overrides the base implementation of onObjectNotFound. Whenever
* this event occurs, look through all the active domains (places
* where objects might be found). For HTML domains (Java
* and other domains are skipped) finds all the top objects.
* If the top object is an Html Dialog,
* types an Enter key to dismiss the dialog.
* Logs a warning when this happens.
*/
public void onObjectNotFound(ITestObjectMethodState testObjectMethodState)
{
if (!testObjectMethodState.getTestObject().
getPropertyFromMap(IMapPropertyName.DOMAIN).equals("Html"))
{
return;
}
boolean dismissedAWindow = false;
DomainTestObject domains[] = getDomains();
for (int i = 0; i < domains.length; ++i)
{
if (domains[i].getName().equals("Html"))
{
// HTML domain is found.
TestObject[] topObjects = domains[i].getTopObjects();
if (topObjects != null)
{
try
{
for (int j = 0; j < topObjects.length; ++j)
{
if (topObjects[j].getProperty(".class").equals("Html.Dialog"))
{
// A top-level HtmlDialog is found.
logWarning("HtmlScript.onObjectNotFound - dismissing dialog.");
try
{
dismissedAWindow = true;
((TopLevelTestObject)topObjects[j]).inputKeys("{enter}");
}
catch(RuntimeException e) {}
}
}
}
finally
{
//unregister all references to top objects
unregister(topObjects);
}
}
}
}
if (dismissedAWindow)
{
// try again
testObjectMethodState.findObjectAgain();
}
else
{
logWarning("HtmlScript.onObjectNotFound; no Html Dialog to dismiss");
}
}