本主题解释了 CreatXPath 挂钩如何允许您创建可用来识别记录 web 场景测试时的元素的自定义定位器的。然后使用这些自定义定位器来进行验证和提取。
本章包含:
关于 Hooks
自定义挂钩可用于记录或修改执行期间在特定点传递的值。
挂钩在脚本中使用自定义方法定义和自定义。同一个文件可以定义多个挂钩。如果向一个挂钩添加多个方法,则在调用该挂钩时将执行该挂钩定义的所有方法。
您可以以在 SOAtest中创建、应用和调用其他脚本相同的方式创建、应用和调用脚本:在启动时(只针对 JavaScript 和 Jython 脚本),通过创建和应用扩展工具,通过向特定路径节点添加脚本来定义挂钩。您可以在不同的时间调用挂钩以引出所需的功能。例如,如果想要将脚本的挂钩功能应用于所有项目和网址,则可以将定义并使用该挂钩的 JavaScript 或 Jython 脚本添加到 <install_dir>/plugins/com.parasoft.xtest.libs.web_<version>/root/startup 目录;然后,任何调用该挂钩的时候,都将执行相关联的用户指定方法。将会一直执行该方法,直到调用该挂钩上的 clear()。
关于 CreateXPath 挂钩
当录制 web 场景时,SOAtest 通过这些元素的某些属性标识与之交互的元素。例如,SOAtest 将使用元素的 ID 或元素的文本内容来定位该元素。如果需要扩展属性来识别功能测试期间的元素,则可以使用 CreateXPath 挂钩。
CreateXPath 挂钩接收两个参数。第一个参数是 org.w3c.dom.Node 的实例,是定位器将为其构建的节点。第二个参数是 org.w3c.dom.Document 的实例,是节点所在的文档。CreateXPath 功能应返回识别文档中节点的 XPath,或如果不能创建 XPath,则返回 null。
例如,如果希望通过它们的“class”属性来识别元素,则可以使用 CreatXPath 挂钩来创建自定义标识符,检查元素的“calss”属性,如果找到一个,返回一个通过“class”属性的值来标识元素 XPath。
当选择要验证的元素,或在录制期间单击元素时,SOAtest 将使用该自定义挂钩。元素将传递给自定义挂钩,然后该挂钩将检查元素的“class”属性。如果找到一个,则将返回一个 XPath,使用“class”属性值来标识元素。
下面是标识元素的示例脚本,使用“class”属性和索引(当多个节点具有相同“class”时)。
app = Packages.com.parasoft.api.Application;
settings = Packages.webtool.browsertest.XPathCreator;
// establish the locator builder priority order
// we use our custom locator after using the id, name and attribute locators // and before using the position xpath locator
settings.locatorBuildersOrder[0] = settings.ID_LOCATOR;
settings.locatorBuildersOrder[1] = settings.NAME_LOCATOR;
settings.locatorBuildersOrder[2] = settings.ATTRIBUTE_XPATH_LOCATOR;
settings.locatorBuildersOrder[3] = settings.HOOK_LOCATOR;
settings.locatorBuildersOrder[4] = settings.POSITION_XPATH_LOCATOR;
// gets the index of the node out of a list of nodes returned using xpath.
function getIndex(xpath, node, doc) {
index = -1;
if (doc) {
try {
list = Packages.org.apache.xpath.XPathAPI.selectNodeList(doc, xpath);
count = 0;
while (index == -1 && count < list.getLength()) {
candidate = list.item(count);
if (candidate.equals(node)) {
index = count;
} else {
++count;
}
}
} catch (e) {}
}
return index;
}
// the hook function to link to the CreateXPath hook.
// looks for the class attribute and uses it (along with an index) to create
// a locator for the given node.
function createXPathHook(node, doc) {
nodeName = node.getNodeName();
attributes = node.getAttributes();
classValue = attributes.getNamedItem("class");
if (classValue) {
xpath = "//" + nodeName + "[@"+ classValue + "]";
index = getIndex(xpath, node, doc);
if (index != -1) {
return xpath + "[" + index + "]";
}
}
return null;
}
// sets up the hook
function setHook() {
hook = app.getHook("CreateXPath");
hook.set(createXPathHook);
}