Selenium学习笔记之外部化相关测试数据---xml

时间:2023-03-09 05:54:32
Selenium学习笔记之外部化相关测试数据---xml

我们也可以用xml来定义一个信息更为丰富的UIMap.xml文件,比如,额外还添加控件所属的页,控件的类型,然后解析构建一个XMLParser类来读取相应的值。

 <?xml version="1.0" encoding="utf-8" ?>
<UIMap>
<Object ID="User Name">
<Attributes Locator="userName" Page="Main Page" Type="Button"/>
</Object> <Object ID="Password">
<Attributes Locator="Password" Page="Main Page" Type="Button"/>
</Object>
</UIMap>

相应的解析xml的代码:

     public static String getLocator(String locatorID){
InputStream ins=Thread.currentThread().getContextClassLoader()
.getResourceAsStream(FileConstants.XMLFILE_NAME);
if(ins==null){
System.out.println("Missing UIMap.xml file.");
return null;
} DocumentBuilderFactory fac=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=null;
try {
builder = fac.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.out.println("Failing to new DocumentBuilder for runtime exception.");
throw new RuntimeException(pce);
} Document xmlDoc=null;
try {
xmlDoc = builder.parse(ins);
} catch (SAXException se) {
System.out.println("Failing to parse xml file for runtime exception.");
throw new RuntimeException(se);
} catch (IOException ie) {
System.out.println("Failing to parse xml file for runtime exception.");
throw new RuntimeException(ie);
} XPathFactory pathFac=XPathFactory.newInstance();
XPath xpath = pathFac.newXPath(); XPathExpression exp=null;
try {
exp = xpath.compile("UIMap/Object[@ID='"+locatorID+"']/Attributes");
} catch (XPathExpressionException e) {
System.out.println("Failing to get locator for :"+locatorID);
}
Node node=null;
try {
node = (Node)exp.evaluate(xmlDoc, XPathConstants.NODE);
} catch (XPathExpressionException e) { e.printStackTrace();
}finally{
try{
if(ins!=null){
ins.close();
}
}catch(Exception ex){
System.out.println("Failing to load UIMap.xml for runtime exception.");
throw new RuntimeException(ex);
}
} return node.getAttributes().getNamedItem("Locator").getNodeValue();
}

测试代码:

 selenium.type(UIMapParser.getLocator("UserName"), "seleniumtest");
selenium.type(UIMapParser.getLocator("Password"), "seleniumtest");