51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 2028|回复: 1
打印 上一主题 下一主题

selenium测试框架篇,页面对象和元素对象的管理

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2018-5-29 16:06:07 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
做自动化框架,不可避免的就是对象库。

有一个好的对象库,可以让整个测试体系:

更容易维护
大大增加代码重用
增加测试系统的稳定性
这里先了解一下我所说的对象库:



所谓的页面对象,是指每一个真是的页面是一个对象。

比如zhihu的登陆页面是一个页面对象,http://www.zhihu.com/#signin

这个页面对象主要包含一个输入邮箱的输入框(一个元素对象),一个输入密码的密码框

一个登陆框。当然,zhihu不止一个页面,有无数页面,每一个页面都可以封装为一个对象。而每个

页面的元素,也可以封装成一个个元素对象。



为什么要封装成一个个对象?

还是以这个登陆页面为例,如果有一天zhihu改版,登陆界面UI变了,(但是需要输入用户名和密码还
有登陆按钮不会消失吧)。

登陆页面的元素的位置也相应改变,如果你的测试用例没有封装过页面和元素, 每个页面都是拿webdr
iver 直接写,页面元素定位

也分布到测试用例中,这要维护起来要全部改掉测试用例。如果你封装了页面,封装了元素,再封装
一个对应的登陆Action,你的每个

测试用例是调用的login.action()。  这样,你只需要改变你对象库的内容就完美解决UI变化,而
不必一个个修改测试用例。

测试框架目录如下:



接下来一这个登陆为例:

首先封装一个BasePage的类,毕竟所有的页面都有共同的东西,每个页面都有元素,每个页面元素都有相应的方法

这里简单封装了几个方法,如type



  1. package com.dbyl.libarary.utils;

  2. import java.io.IOException;

  3. import org.openqa.selenium.By;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.WebElement;
  6. import org.openqa.selenium.interactions.Actions;
  7. import org.openqa.selenium.support.ui.ExpectedCondition;
  8. import org.openqa.selenium.support.ui.WebDriverWait;

  9. public class BasePage {

  10.     protected WebDriver driver;
  11.     protected String[][] locatorMap;

  12.     protected BasePage(WebDriver driver) throws IOException {
  13.         this.driver = driver;
  14.         locatorMap = ReadExcelUtil.getLocatorMap();
  15.     }

  16.     protected void type(Locator locator, String values) throws Exception {
  17.         WebElement e = findElement(driver, locator);
  18.         e.sendKeys(values);
  19.     }

  20.     protected void click(Locator locator) throws Exception {
  21.         WebElement e = findElement(driver, locator);
  22.         e.click();
  23.     }

  24.     protected void clickAndHold(Locator locator) throws IOException {
  25.         WebElement e = findElement(driver, locator);
  26.         Actions actions = new Actions(driver);
  27.         actions.clickAndHold(e).perform();
  28.     }

  29.     public WebDriver getDriver() {
  30.         return driver;
  31.     }

  32.     public void setDriver(WebDriver driver) {
  33.         this.driver = driver;
  34.     }

  35.     public WebElement getElement(Locator locator) throws IOException {
  36.         return getElement(this.getDriver(), locator);
  37.     }

  38.     /**
  39.      * get by parameter
  40.      *
  41.      * @author Young
  42.      * @param driver
  43.      * @param locator
  44.      * @return
  45.      * @throws IOException
  46.      */
  47.     public WebElement getElement(WebDriver driver, Locator locator)
  48.             throws IOException {
  49.         locator = getLocator(locator.getElement());
  50.         WebElement e;
  51.         switch (locator.getBy()) {
  52.         case xpath:
  53.             e = driver.findElement(By.xpath(locator.getElement()));
  54.             break;
  55.         case id:
  56.             e = driver.findElement(By.id(locator.getElement()));
  57.             break;
  58.         case name:
  59.             e = driver.findElement(By.name(locator.getElement()));
  60.             break;
  61.         case cssSelector:
  62.             e = driver.findElement(By.cssSelector(locator.getElement()));
  63.             break;
  64.         case className:
  65.             e = driver.findElement(By.className(locator.getElement()));
  66.             break;
  67.         case tagName:
  68.             e = driver.findElement(By.tagName(locator.getElement()));
  69.             break;
  70.         case linkText:
  71.             e = driver.findElement(By.linkText(locator.getElement()));
  72.             break;
  73.         case partialLinkText:
  74.             e = driver.findElement(By.partialLinkText(locator.getElement()));
  75.             break;
  76.         default:
  77.             e = driver.findElement(By.id(locator.getElement()));
  78.         }
  79.         return e;
  80.     }

  81.     public boolean isElementPresent(WebDriver driver, Locator myLocator,
  82.             int timeOut) throws IOException {
  83.         final Locator locator = getLocator(myLocator.getElement());
  84.         boolean isPresent = false;
  85.         WebDriverWait wait = new WebDriverWait(driver, 60);
  86.         isPresent = wait.until(new ExpectedCondition<WebElement>() {
  87.             @Override
  88.             public WebElement apply(WebDriver d) {
  89.                 return findElement(d, locator);
  90.             }
  91.         }).isDisplayed();
  92.         return isPresent;
  93.     }

  94.     /**
  95.      * This Method for check isPresent Locator
  96.      *
  97.      * @param locator
  98.      * @param timeOut
  99.      * @return
  100.      * @throws IOException
  101.      */
  102.     public boolean isElementPresent(Locator locator, int timeOut)
  103.             throws IOException {
  104.         return isElementPresent(driver,locator, timeOut);
  105.     }

  106.     /**
  107.      *
  108.      * @param driver
  109.      * @param locator
  110.      * @return
  111.      */
  112.     public WebElement findElement(WebDriver driver, final Locator locator) {
  113.         WebElement element = (new WebDriverWait(driver, locator.getWaitSec()))
  114.                 .until(new ExpectedCondition<WebElement>() {

  115.                     @Override
  116.                     public WebElement apply(WebDriver driver) {
  117.                         try {
  118.                             return getElement(driver, locator);
  119.                         } catch (IOException e) {
  120.                             // TODO Auto-generated catch block
  121.                             return null;
  122.                         }

  123.                     }

  124.                 });
  125.         return element;

  126.     }

  127.     public Locator getLocator(String locatorName) throws IOException {

  128.         Locator locator;
  129.         for (int i = 0; i < locatorMap.length; i++) {
  130.             if (locatorMap[i][0].endsWith(locatorName)) {
  131.                 return locator = new Locator(locatorMap[i][1]);
  132.             }
  133.         }

  134.         return locator = new Locator(locatorName);

  135.     }
  136. }
复制代码

接下来封装元素,Webdriver的元素,每个元素都有相应的定位地址(xpath路径或css或id)等待时间和定位类型,默认为By.xpath

  1. package com.dbyl.libarary.utils;

  2. /**
  3. * This is for element library
  4. *
  5. * @author Young
  6. *
  7. */
  8. public class Locator {
  9.     private String element;

  10.     private int waitSec;

  11.     /**
  12.      * create a enum variable for By
  13.      *
  14.      * @author Young
  15.      *
  16.      */
  17.     public enum ByType {
  18.         xpath, id, linkText, name, className, cssSelector, partialLinkText, tagName
  19.     }

  20.     private ByType byType;

  21.     public Locator() {

  22.     }

  23.     /**
  24.      * defaut Locator ,use Xpath
  25.      *
  26.      * @author Young
  27.      * @param element
  28.      */
  29.     public Locator(String element) {
  30.         this.element = element;
  31.         this.waitSec = 3;
  32.         this.byType = ByType.xpath;
  33.     }

  34.     public Locator(String element, int waitSec) {
  35.         this.waitSec = waitSec;
  36.         this.element = element;
  37.         this.byType = ByType.xpath;
  38.     }

  39.     public Locator(String element, int waitSec, ByType byType) {
  40.         this.waitSec = waitSec;
  41.         this.element = element;
  42.         this.byType = byType;
  43.     }

  44.     public String getElement() {
  45.         return element;
  46.     }

  47.     public int getWaitSec() {
  48.         return waitSec;
  49.     }

  50.     public ByType getBy() {
  51.         return byType;
  52.     }

  53.     public void setBy(ByType byType) {
  54.         this.byType = byType;
  55.     }

  56. }
复制代码


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏3
回复

使用道具 举报

该用户从未签到

2#
 楼主| 发表于 2018-5-29 16:06:25 | 只看该作者

接下来就是登陆页面的类,这个登陆页面的元素,放在excel统一管理,要获取元素的信息,首先从excel读取。

读取excel的页面元素是使用POI开源框架

package com.dbyl.libarary.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class ReadExcelUtil {

static String path;

/**
* @author Young
* @return
* @throws IOException
*/
public static String[][] getLocatorMap() throws IOException {
path = "C:/Users/Young/workspace/Demo/src/com/dbyl/libarary/pageAction/UILibrary.xls";
File f1 = new File(path);
FileInputStream in = new FileInputStream(f1);
HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(in));
Sheet sheet = wb.getSheetAt(0);
Row header = sheet.getRow(0);
String[][] locatorMap = new String[sheet.getLastRowNum() + 1][header
.getLastCellNum()];
for (int rownum = 0; rownum <= sheet.getLastRowNum(); rownum++) {
// for (Cell cell : row)
Row row = sheet.getRow(rownum);

if (row == null) {

continue;

}
String value;
for (int cellnum = 0; cellnum <= row.getLastCellNum(); cellnum++) {
Cell cell = row.getCell(cellnum);
if (cell == null) {
continue;
} else {
value = "";
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
value = cell.getDateCellValue().toString();

} else {
value = Double.toString((int) cell
.getNumericCellValue());

}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula().toLowerCase();
break;
default:
value = " ";
System.out.println();
}
locatorMap[rownum][cellnum] = value;

}
}
in.close();
wb.close();

return locatorMap;
}

}

页面类

复制代码
package com.dbyl.libarary.pageAction;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import com.dbyl.libarary.utils.BasePage;
import com.dbyl.libarary.utils.Locator;

public class LoginPage extends BasePage {

WebDriver driver;

public WebDriver getDriver() {
return driver;
}

public LoginPage(WebDriver driver) throws IOException {
super(driver);
driver.get("http://www.zhihu.com/#signin");
}

Locator loginEmailInputBox = new Locator("loginEmailInputBox");

Locator loginPasswordInputBox = new Locator("loginPasswordInputBox");
Locator loginButton = new Locator("loginButton");
Locator profile = new Locator(
"profile");

public void typeEmailInputBox(String email) throws Exception {
type(loginEmailInputBox, email);
}

public void typePasswordInputBox(String password) throws Exception {
type(loginPasswordInputBox, password);
}

public void clickOnLoginButton() throws Exception {
click(loginButton);
}

public boolean isPrestentProfile() throws IOException {
return isElementPresent(profile, 20);

}

public void waitForPageLoad() {
super.getDriver().manage().timeouts()
.pageLoadTimeout(30, TimeUnit.SECONDS);
}


}

复制代码
接下来就是登陆的Action

复制代码
package com.dbyl.libarary.action;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;

import com.dbyl.libarary.pageAction.HomePage;
import com.dbyl.libarary.pageAction.LoginPage;

public class CommonLogin {

private static WebDriver driver;

public static WebDriver getDriver() {
return driver;
}

static LoginPage loginPage;

public static HomePage login(String email, String password)
throws Exception {
loginPage = new LoginPage(getDriver());
loginPage.waitForPageLoad();
loginPage.typeEmailInputBox(email);
loginPage.typePasswordInputBox(password);
loginPage.clickOnLoginButton();
Assert.assertTrue(loginPage.isPrestentProfile(), "login failed");
return new HomePage(getDriver());
}

public static HomePage login() throws Exception {
return CommonLogin.login("seleniumcookies@126.com", "cookies123");
}

public static void setDriver(WebDriver driver) {
CommonLogin.driver = driver;
}

}

复制代码
至此为止,已经封装完毕

接下来就能在测试用例直接调用者

package com.dbyl.tests;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.dbyl.libarary.action.ViewHomePage;
import com.dbyl.libarary.utils.DriverFactory;
import com.dbyl.libarary.utils.UITest;

public class loginTest extends UITest{


WebDriver driver=DriverFactory.getChromeDriver();
@BeforeMethod(alwaysRun=true)
public void init()
{
super.init(driver);
ViewHomePage.setDriver(driver);
//CommonLogin.setDriver(driver);
}
@Test(groups="loginTest")
public void loginByUerName() throws Exception
{
//CommonLogin.login("seleniumcookies@126.com","cookies123");
ViewHomePage.viewMyProfile();
}

@AfterMethod(alwaysRun=true)
public void stop() {
super.stop();
}
回复 支持 反对

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-9-20 23:41 , Processed in 0.066776 second(s), 24 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表