当我们以脚本形式编写了大量自动化测试代码后,常常会陷入困境:代码可读性差、脚本几乎无法扩展,或者每次修改都如同“打补丁”。更糟糕的是,一旦被测系统的UI发生变更,测试代码的修改就是一场灾难。整个自动化工程结构混乱,这已经部分丧失了自动化测试本应带来的效率优势。
任何自动化测试团队在启动项目前,都必须评估其投入产出比。自动化测试的初衷是解放人力,但前述的混乱状况不仅导致ROI极低,也完全违背了这一初衷。
在此背景下,引入PO模式成为必然。PO(Page Object)模式是一种自动化测试的设计模式,也是一种解耦思想。其核心是以页面为单位,将页面中的控件及控件的操作逐一抽象封装,使得测试脚本可以直接调用这些封装好的对象。最终目的是实现元素定位表达式、页面对象和测试脚本代码三者的分离。
分离后的测试代码,将具备极高的可复用性、可读性、可维护性和扩展性。这种思想与面向对象编程一脉相承,也类似于Java中Spring的MVC模式或Django的MTV模式。
定义页面类
我们以一个登录页面为例,展示如何定义页面类。这里使用Selenium WebDriver和PageFactory。
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
public class LoginPage {
//使用FindBy注解,定位到要操作的页面元素, 此处用的xpath,也可以用其他的类型
@FindBy(xpath = "//*[@name='email']")
public WebElement userName;
@FindBy(xpath = "//*[@name='password']")
public WebElement passWord;
@FindBy(xpath = "//*[@id ='dologin']")
public WebElement loginButton;
public String url = "http://mail.126.com";
public String title= "网易免费邮箱";
public WebDriver driver;
//构造函数,生成浏览器对象,初始化PageFactory对象
public LoginPage(){
driver = new ChromeDriver();
PageFactory.initElements(driver, this);
}
public void load(){
this.driver.get(url);
}
public void quit(){
driver.quit();
}
public void login(){
driver.switchTo().frame(driver.findElement(By.xpath("//*[@id='x-URS-iframe']")));
userName.sendKeys("davieyang99@126.com");
passWord.sendKeys("alex005x");
loginButton.click();
}
public WebDriver getDriver(){
return driver;
}
public void isLoaded()throws Error{
Assert.assertTrue(driver.getTitle().contains(title));
}
}
简洁的测试脚本
结合Java的单元测试框架TestNG完成测试脚本编写。可以看到,测试脚本变得非常清晰,只关注测试逻辑,而不涉及具体的元素定位细节。
package TestScripts;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import PageObjects.LoginPage;
public class Test126mail {
private WebDriver driver;
/*private String baseUrl="http://mail.126.com";
@BeforeMethod
public void beforeMethod(){
driver = new ChromeDriver();
}*/
@Test
public void testLogin() throws InterruptedException {
LoginPage loginpage = new LoginPage();
loginpage.load();
Thread.sleep(1000);
loginpage.login();
Thread.sleep(3000);
/*
loginpage.userName.sendKeys("davieyang99");
loginpage.passWord.sendKeys("alex005x");
loginpage.loginButton.click();
*/
Assert.assertTrue(loginpage.getDriver().getPageSource().contains("邮件"));
loginpage.quit();
}
/*@AfterMethod
public void afterMethod(){
driver.quit();
}*/
}
PO设计模式II:更彻底的分离
上面的示例将元素定位与页面类绑定,是一种常见做法。另一种更彻底的做法是将所有元素定位信息剥离到外部配置文件中,实现更灵活的管理。
定义页面元素
自动化测试的根源在于页面元素。控制控件的前提是获取其位置。我们讨论的不是定位方式本身,而是如何管理这些定位表达式以实现分离。
在自动化测试工程中新建一个属性文件(例如 MysqlService.properties),建议以页面为单位进行分离。内容格式为:控件名=定位方式>定位表达式。
[MySQL数据库服务]
[MySQL数据库服务-列表]
paas.mysql.refreshbutton=xpath>//*[@id='app']/section/section/main/div[2]/div/div[5]/button
paas.mysql.createnewinstance=xpath>//*[@id='app']/section/section/main/div[2]/div/div[4]/button
paas.mysql.searchinstancenameinput=xpath>//*[@id="app"]/section/section/main/div[2]/div/div[1]/label[1]/div/input
paas.mysql.searchinstancenamebutton=xpath>//*[@id='app']/section/section/main/div[2]/div/div[1]/label[2]/button
paas.mysql.searchspacename=xpath>//*[@id='app']/section/section/main/div[2]/div/div[3]/label[2]/div/div[1]/input
paas.mysql.operation=xpath>//*[@id='app']/section/section/main/section/div[1]/div[3]/table/tbody/tr[1]/td[6]/div/div/span
paas.mysql.operationrestart=xpath>/html/body/ul/li[1]
paas.mysql.operationrelease=xpath>/html/body/ul/li[2]
paas.mysql.operationmanage=xpath>/html/body/ul/li[3]
paas.mysql.operationlog=xpath>/html/body/ul/li[4]
paas.mysql.operationmonitor=xpath>/html/body/ul/li[5]
paas.mysql.confirmrestart=xpath>/html/body/div[1]/div/div[3]/button[2]
paas.mysql.cancelrestart=xpath>/html/body/div[1]/div/div[3]/button[1]
paas.mysql.releaseconfirmbutton=xpath>/html/body/div[1]/div/div[3]/button[2]
paas.mysql.releasecancelbutton=xpath>/html/body/div[1]/div/div[3]/button[1]
[MySQL数据库服务-创建]
paas.newinstance.instancename=xpath>//*[@id='app']/section/section/main/div[3]/div/div[2]/main/form/div[2]/div/div[1]/input
paas.newinstance.description=xpath>//*[@id='app']/section/section/main/div[3]/div/div[2]/main/form/div[10]/div/div/textarea
paas.newinstance.standard5.6=xpath>//*[@id='app']/section/section/main/div[3]/div/div[2]/main/form/div[4]/div/div/label[1]/span
paas.newinstance.standard5.7=xpath>//*[@id='app']/section/section/main/div[3]/div/div[2]/main/form/div[4]/div/div/label[2]/span
paas.newinstance.instancestandard=xpath>//*[@id='app']/section/section/main/div[3]/div/div[2]/main/form/div[5]/div/div/div[1]/input
paas.newinstance.1c1gb=xpath>/html/body/div[2]/div[1]/div[1]/ul/li[1]
paas.newinstance.1c2gb=xpath>/html/body/div[2]/div[1]/div[1]/ul/li[2]
paas.newinstance.2c8gb=xpath>/html/body/div[2]/div[1]/div[1]/ul/li[3]
公共类方法
定义公共工具类,用于解析配置文件,获取元素定位,并返回页面元素对象。
/*
* @FileName GetElementUtil: this util is use for getting page element
* @author davieyang
* @create 2018-08-21 16:37
*/
package util;
import org.openqa.selenium.By;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class GetElementUtil {
private Properties properties;
/**
* 用于读取存储页面元素的属性文件
* @param propFile 属性文件的绝对路径,应定义为常量
*/
public GetElementUtil(String propFile){
properties = new Properties();
try{
FileInputStream in = new FileInputStream(propFile);
properties.load(in);
in.close();
}catch (IOException e){
System.out.println("读取对象文件出错");
e.printStackTrace();
}
}
/**
* @param elementName 存储在属性文件中的元素名称"pass.spacemanagement.releasebutton"
* @return 根据传入的页面元素名获取元素,返回元素定位
* @throws Exception "输入的locator Type 未在程序中定义:" + locatorType
*/
public By getLocator(String elementName) throws Exception{
//根据变量ElementNameInproFile,从属性配置文件中读取对应的配置对象
String locator = properties.getProperty(elementName);
//将配置对象中的定位类型存到locatorType变量,将定位表达式的值存到locatorValue变量
String locatorType = locator.split(">")[0];
String locatorValue = locator.split(">")[1];
/**
* 配置文件均默认为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.tagName(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);
}
/**
*
* @param driver 浏览器驱动
* @param element 页面元素对象
*/
public static void highLightElement(WebDriver driver, WebElement element){
JavascriptExecutor js = (JavascriptExecutor) driver;
/*调用js将传入参数的页面元素对象的背景颜色和边框颜色分别设定为黄色和红色*/
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "background: yellow; border:2px solid red;");
}
}
页面元素对象封装
通过公共工具类读取配置文件中的定位信息,将每个页面控件封装成独立的可操作方法。
/*
* @FileName StoreManagement: 封装Mysql页面对象
* @outhor davieyang
* @create 2018-08-08 11:12
*/
package pageobject.resourcemanagement;
import util.GetElementUtil;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import static constants.Constants.MysqlService_Property;
import static util.GetElementUtil.highLightElement;
public class MySQLService {
private static WebElement element = null;
/**指定页面元素定位表达式配置文件的绝对路径
*
*/
private static GetElementUtil getElementUtil = new GetElementUtil(MysqlService_Property);
private WebDriver driver;
public MySQLService(WebDriver driver){
this.driver = driver;
}
/**返回MySQL数据库服务页面“刷新”按钮的页面元素对象
*
* @param driver 浏览器驱动
* @return
* @throws Exception 获取定位信息失败
*/
public static WebElement refresh_Button(WebDriver driver) throws Exception{
//调用GetElementUtil中的getLocator方法获取配置文件中关于用户名的定位方式和定位表达式
element = driver.findElement(getElementUtil.getLocator("paas.mysql.refreshbutton"));
highLightElement(driver, element);
return element;
}
/**返回MySQL数据库服务页面“创建实例”按钮的页面元素对象
*
* @param driver 浏览器驱动
* @return
* @throws Exception 获取定位信息失败
*/
public static WebElement create_New_Instance_Button(WebDriver driver) throws Exception{
//调用GetElementUtil中的getLocator方法获取配置文件中关于用户名的定位方式和定位表达式
element = driver.findElement(getElementUtil.getLocator("paas.mysql.createnewinstance"));
highLightElement(driver, element);
return element;
}
/**
*
* @param driver
* @return
* @throws Exception
*/
public static WebElement search_Instance_Name_Input(WebDriver driver) throws Exception{
//调用GetElementUtil中的getLocator方法获取配置文件中关于用户名的定位方式和定位表达式
element = driver.findElement(getElementUtil.getLocator("paas.mysql.searchinstancenameinput"));
highLightElement(driver, element);
return element;
}
/**返回MySQL数据库服务页面MySQL名称检索控件的页面元素对象
*
* @param driver 浏览器驱动
* @return
* @throws Exception 获取定位信息失败
*/
public static WebElement search_Instance_Name_Button(WebDriver driver) throws Exception{
//调用GetElementUtil中的getLocator方法获取配置文件中关于用户名的定位方式和定位表达式
element = driver.findElement(getElementUtil.getLocator("paas.mysql.searchinstancenamebutton"));
highLightElement(driver, element);
return element;
}
/**返回MySQL数据库服务页面运行空间检索控件页面元素对象
*
* @param driver 浏览器驱动
* @return
* @throws Exception 获取定位信息失败
*/
public static WebElement search_Space_Name(WebDriver driver) throws Exception{
//调用GetElementUtil中的getLocator方法获取配置文件中关于用户名的定位方式和定位表达式
element = driver.findElement(getElementUtil.getLocator("paas.mysql.searchspacename"));
highLightElement(driver, element);
return element;
}
}
简洁的测试脚本
结合TestNG框架,最终的测试脚本将极其清晰,只描述业务流程和验证点。
package testscript;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.*;
import org.testng.Assert;
import org.testng.annotations.*;
import util.KeyActionsUtil;
import static util.KeyActionsUtil.*;
import java.util.List;
import static appmodule.MysqlService.linkToMysqlPage;
import static util.KeyBoardUtil.pressTabKey;
import static util.LogUtil.info;
import static pageobject.resourcemanagement.MySQLService.*;
import static util.ScrollBarUtil.scrolltoBottom;
import static util.WaitElementUtil.sleep;
// @Listeners({util.TestReport.class})
public class Test_Mysql {
static {
DOMConfigurator.configure("log4j.xml");
}
@BeforeClass
public void setUp()throws Exception {
WebDriver driver = KeyActionsUtil.initBrowser("chrome");
linkToMysqlPage(driver, "yangdawei", "alex005x");
sleep(2000);
}
@Test(priority = 0, description = "测试创建mysql数据库服务1CPU2G")
public void test_CreateMysqlInstance() throws Exception {
create_New_Instance_Button(driver).click();
info("点击创建实例按钮...");
sleep(1000);
info("等待3秒...");
instance_Name_in_Create_Instance_Dialog(driver).sendKeys("automationtest");
info("输入实例名:automationtesta");
sleep(1000);
info("等待3秒...");
//页面存在相同属性的元素,取所有放到list里,用序号操作
List<WebElement> radios = driver.findElements(By.className("el-radio-button__inner"));
radios.get(1).click();
sleep(1000);
info("选择数据库版本5.7...");
instance_Standard_in_Create_Instance_Dialog(driver).click();
info("点击实例规格...");
sleep(2000);
info("等待2秒...");
one_Core_two_GB(driver).click();
info("选择1CPU2GB...");
storage_Space_in_Create_Instance_Dialog(driver).clear();
info("清空存储空间字段...");
storage_Space_in_Create_Instance_Dialog(driver).sendKeys("1");
info("输入1G....");
scrolltoBottom(driver);
sleep(2000);
pressTabKey();
outsideaccess_Checkbox_in_Create_Instance_Dialog(driver).click();
info("选择外部链接...");
password_in_Create_Instance_Dialog(driver).sendKeys("111111");
info("输入密码111111...");
repassword_in_Create_Instance_Dialog(driver).sendKeys("111111");
info("确认密码111111...");
description_in_Create_Instance_Dialog(driver).sendKeys("automationtest");
info("描述信息输入automationtest");
sleep(2000);
submit_Button_in_Create_Instance_Dialog(driver).sendKeys(Keys.ENTER);
info("确认创建...");
sleep(2000);
refresh_Button(driver).click();
Assert.assertTrue(driver.getPageSource().contains("automationtest"));
Assert.assertTrue(driver.getPageSource().contains("创建中"));
}
@Test(priority = 1, description = "重启mysql服务")
public void test_RestartMysqlInstance()throws Exception {
operation_Button(driver).click();
info("点击列表里最后一列的...");
sleep(2000);
info("等待3秒...");
operation_Restart_Button(driver).click();
info("点击下拉菜单中的重启按钮...");
sleep(2000);
info("等待3秒...");
restart_Confirm_Button(driver).click();
info("点击确定按钮...");
sleep(2000);
info("等待3秒...");
Assert.assertTrue(driver.getPageSource().contains("重启请求成功"));
Assert.assertTrue(driver.getPageSource().contains("重启中"));
}
@Test(priority = 2, description = "管理mysql服务页面")
public void test_Review_Basic_Mysql_Info()throws Exception{
operation_Button(driver).click();
info("点击列表里最后一列的...");
sleep(2000);
info("等待3秒...");
operation_Manage_Button(driver).click();
info("点击下拉菜单里的管理按钮...");
sleep(2000);
info("等待三秒");
assertString(driver,"基本信息");
}
@Test(priority = 3, description = "管理mysql服务页面")
public void test_Review_Mysql_Link()throws Exception{
database_Link_Tab(driver).click();
sleep(2000);
Assert.assertTrue(driver.getPageSource().contains("210.13.50.105"));
}
@Test(priority = 4,description = "查看Mysql日志")
public void test_ReviewLog()throws Exception{
operation_Button(driver).click();
info("点击列表里最后一列的...");
sleep(2000);
info("等待3秒...");
operation_Log_Button(driver).click();
info("点击下拉菜单中的日志按钮...");
sleep(2000);
info("等待3秒...");
extend_Button_in_Log_Page(driver).click();
info("点击展开按钮...");
sleep(2000);
info("等待3秒...");
datefrom_in_Log_Page(driver).click();
info("点击第一个日期空间,弹出下拉...");
sleep(2000);
info("等待3秒...");
datefrom_by_Date_in_Log_Page(driver).clear();
datefrom_by_Date_in_Log_Page(driver).sendKeys("2018-09-01");
info("输入日期”2018-09-01");
sleep(2000);
info("等待3秒...");
datefrom_Sure_Button_in_Log_Page(driver).click();
info("点击确定按钮...");
sleep(2000);
info("等待3秒...");
search_Button_in_Log_Page(driver).click();
info("点击筛选按钮...");
sleep(2000);
info("等待3秒...");
Assert.assertTrue(driver.getPageSource().contains("Initializing database"));
}
@Test(priority = 5, description = "查看Mysql服务监控")
public void test_MonitorMysqlService()throws Exception{
operation_Button(driver).click();
info("点击列表里最后一列的...");
sleep(3000);
info("等待3秒...");
operation_Monitor_Button(driver).click();
info("点击下拉菜单里的监控按钮...");
sleep(3000);
info("等待3秒...");
}
@Test(priority = 6, description = "释放mysql服务")
public void test_ReleaseMysqlService()throws Exception{
operation_Button(driver).click();
info("点击列表里最后一列的...");
sleep(3000);
info("等待3秒...");
operation_Release_Button(driver).click();
info("点击下拉菜单里的释放按钮...");
sleep(3000);
info("等待3秒...");
release_Confirm_Button(driver).click();
info("点击确定按钮...");
sleep(3000);
info("等待3秒...");
Assert.assertTrue(driver.getPageSource().contains("操作成功"));
Assert.assertTrue(driver.getPageSource().contains("删除中"));
}
@AfterClass
public void afterMethod(){
driver.quit();
}
}
通过以上两种PO模式的实践对比,我们可以清晰地看到,良好的设计模式应用如何将杂乱的“面条式”脚本重构为结构清晰、易于维护的自动化工程。这不仅提升了代码质量,更从根本上保障了自动化测试活动的长期价值和可持续性。对于希望系统学习更多工程化实践和架构知识的开发者,可以关注云栈社区的相关技术板块,与更多同行交流探讨。