Java Selenium 对象库(UI Map)

    目的:

    能够使用配置文件存储被测试页面上元素的定位方式和定位表达式,做的定位数据和程序分离。测试程序写好以后,可以方便不具备编码能力的测试人员进行自定义修改和设置。

    首先实现 ObjectMap 工具类,供测试程序调用:

package cn.hx.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;

public class ObjectMap {

    Properties properties;

    public ObjectMap(String propFile) {
        properties = new Properties();
        try {
            FileInputStream in = new FileInputStream(propFile);
            properties.load(in);
            in.close();
        } catch (IOException e) {
            System.out.println("读取对象文件出错");
            e.printStackTrace();
        }
    }

    public By getLocator(String ElementNameInpopFile) throws Exception {
        // 根据变量ElementNameInpopFile,从属性配置文件中读取对应的配置对象
        String locator = properties.getProperty(ElementNameInpopFile);
        // 将配置对象中的定位类型存储到locatorType变量,将定位表达式的值存储到locatorValue变量中
        String[] vals = locator.split(">");
        String locatorType = vals[0];
        String locatorValue = vals[1];// 在Eclipse中的配置文件均默认为ISO-8859-1编码存储,使用getBytes方法可以将字符串编码转换为UTF-8编码,以此来解决在配置文件读取中文乱码的问题
        locatorValue = new String(locatorValue.getBytes("ISO-8859-1"), "UTF-8");
        // 输出locatorType变量值和locatorValue变量值,验证是否赋值正确
        System.out.println("获取的定位类型:" + locatorType + "\t 获取的定位表达式:" + locatorValue);
        // 根据locatorType的变量值内容判断返回何种定位方式的By对象
        if (locatorType.toLowerCase().equals("id")) {
            return By.id(locatorValue);
        } else if (locatorType.toLowerCase().equals("name")) {
            return By.name(locatorValue);
        } else if ((locatorType.toLowerCase().equals("classname")) || (locatorType.toLowerCase().equals("class"))) {
            return By.className(locatorValue);
        } else if ((locatorType.toLowerCase().equals("tagname")) || (locatorType.toLowerCase().equals("tag"))) {
            return By.className(locatorValue);
        } else if ((locatorType.toLowerCase().equals("linktext")) || (locatorType.toLowerCase().equals("link"))) {
            return By.linkText(locatorValue);
        } else if (locatorType.toLowerCase().equals("partiallinktext")) {
            return By.partialLinkText(locatorValue);
        } else if ((locatorType.toLowerCase().equals("cssselector")) || (locatorType.toLowerCase().equals("css"))) {
            return By.cssSelector(locatorValue);
        } else if (locatorType.toLowerCase().equals("xpath")) {
            return By.xpath(locatorValue);
        } else {
            throw new Exception("输入的 locator type 未在程序中被定义:" + locatorType);
        }
    }
    
}

 

objectMap.properties 存储的元素定位表达式文件内容:

speedTest.lineLogin.submitBtn=id>submit_button
speedTest.lineLogin.selUsType=id>userType4
speedTest.lineLogin.famUserNo=id>userNo1

    测试页面中的所有页面元素的定位方式和定位表达式均可在此文件中进行定义,实现定位数据和测试程序的分离。在一个配置文件中修改定位数据,可以在测试脚本全局生效,此方式可以大大提高定位表达式的维护效率。

posted @ 2017-04-13 11:11  SunnyCC  阅读(422)  评论(0)    收藏  举报