抄来的

it2026-04-16  2

 

原作者:http://blog.sina.com.cn/s/articlelist_1371809337_1_1.html

分离页面操作01-PageElement 页面元素提取

1.页面元素的提取 package com.app.pageobjects; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class PageElement {     // 登录     @FindBy(className = "login")     private WebElement login;     // 登陆名     @FindBy(id = "login_name_d")     // 缓存     // @CacheLookup     private WebElement loginName;     // 密码     @FindBy(id = "login_pass_d")     // @CacheLookup     private WebElement loginPass;     // 记住登录状态     @FindBy(id = "login_save")     private WebElement loginSave;     // 登录按钮     @FindBy(id = "login_button")     @CacheLookup     private WebElement loginButton;     // 登录失败断言     @FindBy(id = "login_div_error")     private WebElement loginDivError;     // 登录成功断言     @FindBy(xpath = "//a[@id='SG_Publish']/em")     private WebElement sgPublish;     public PageElement(WebDriver dr) {         PageFactory.initElements(dr, this);     }     public WebElement getLogin() {         return login;     }     public WebElement getLoginName() {         return loginName;     }     public WebElement getLoginPass() {         return loginPass;     }     public WebElement getLoginSave() {         return loginSave;     }     public WebElement getLoginButton() {         return loginButton;     }     public WebElement getLoginDivError() {         return loginDivError;     }     public WebElement getSgPublish() {         return sgPublish;     } }

分离页面操作02-ElementAction 页面元素动作

2.页面元素的操作 使用到的类:WebDriverInstance,PageElement WebDriverInstance-用来获得webdriver实例.根据传递的参数,获得不同浏览器的实例; PageElement-用来获得页面元素 package com.app.pageobjects; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import com.app.publics.Browsers; public class ElementAction {     private String baseUrl;     public final WebDriver driver;     public final PageElement pageElement;     private static ElementAction elementAction;     private ElementAction(String browser) {         //根据传递的参数初始化driver         driver = WebDriverInstance.getDriver(browser);         baseUrl = "http://blog.sina.com.cn/dlr521sara";         // 隐性等待         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);         // 页面加载,仅适用于ff         driver.manage().timeouts().pageLoadTimeout(2000, TimeUnit.SECONDS);         // 窗口最大化         driver.manage().window().maximize();         // 清楚所有cookie         driver.manage().deleteAllCookies();         pageElement = new PageElement(this.driver);     }     public static ElementAction getInstance(String browser) {         if (elementAction == null)             return new ElementAction(browser);         return elementAction;     }     public void load() {         driver.get(baseUrl);     }     public void login() {         pageElement.getLogin().click();     }     public void loginFailure(String name, String pass)             throws InterruptedException {         pageElement.getLoginName().clear();         pageElement.getLoginName().sendKeys(name);         Thread.sleep(1000);         pageElement.getLoginPass().clear();         pageElement.getLoginPass().sendKeys(pass);         Thread.sleep(1000);         pageElement.getLoginButton().click();         Thread.sleep(1000);     }     public void loginSuccess() {         pageElement.getLoginName().clear();         pageElement.getLoginName().sendKeys("");         pageElement.getLoginPass().clear();         pageElement.getLoginPass().sendKeys("");         pageElement.getLoginButton().click();     }     public void close() {         driver.quit();     }     public String getBaseUrl() {         return baseUrl;     } }

分离页面操作03-WebDriverInstance初始化

3.WebDriverInstance-初始化webdriver实例 package com.app.publics; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public final class WebDriverInstance {     private static WebDriver dr;     private WebDriverInstance(){     }     public static WebDriver getDriver(String str){         if(dr != null)             return dr;         else{             if(str.equals("ff")){                 System.setProperty("webdriver.firefox.bin",                         "D:\\Program Files\\Mozilla Firefox\\firefox.exe");                 dr = new FirefoxDriver();                 return dr;             }             if(str.equals("ie")){                 //IEDriver。exe加载写在此处                 dr = new InternetExplorerDriver();                 return dr;             }             if(str.equals("chrome")){                 //同上                 dr = new ChromeDriver();                 return  dr;             }             else{                 System.out.println("参数错误,只能为 ff/ie/chrome!");                 return null;             }         }     } }

分离页面操作04-HashMapExcel读取数据驱动文件excel

4.读取数据驱动文件excel中内容,并转为二维数组 package com.app.dataProvider; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public final class HashMapExcel {     public static Object[][] getData(HashMap<Integer, Cell[]> hm) {         if (hm == null) {             System.out.println("参数传递错误");             return null;         }         // 将hm中value转为stringBuffer         StringBuffer strBuffer = new StringBuffer();         // StringBuilder strBuilder = new StringBuilder();         for (int i = 1; i < hm.size(); i++) {             for (int j = 0; j < hm.get(i).length; j++) {                 if (String.valueOf(hm.get(i)[j].getContents()).trim()                         .equals("")) {                     continue;                 }                 strBuffer.append(hm.get(i)[j].getContents() + ",");             }             strBuffer.append("\n");         }         // 将stringBuffer转为一维字符串数组         String[] str = new String[hm.size()];         str = strBuffer.toString().split("\n");         for (int i = 0; i < str.length; i++) {             System.out.println(str[i]);         }         // 将一维字符串数组转为二维数组         String[][] s2 = new String[str.length][];         for (int i = 0; i < s2.length; i++) {             s2[i] = str[i].split(",");         }         for (int i = 0; i < str.length; i++) {             for (int j = 0; j < s2[i].length; j++) {                 if (s2[i][j].equals("空"))                     s2[i][j] = "";                 if (s2[i][j].equals("空格"))                     s2[i][j] = "      ";             }         }         return s2;     }     public static void print(HashMap<Integer, Cell[]> hm) {         String value = null;         if (hm == null) {             System.out.println("参数传递错误");             return;         }         // 输出         for (int i = 0; i < hm.keySet().size(); i++) {             for (int j = 0; j < hm.get(i).length; j++) {                 value = hm.get(i)[j].getContents();                 if (!value.equals("")) {                     System.out.print(String.valueOf(hm.get(i)[j].getContents())                             + "\t");                 }             }             System.out.println();         }     }     public static HashMap<Integer, Cell[]> m0(String filePath,             String sheetName, String key) throws IOException, BiffException {         // 判断文件是否有效         if (!isFilePath(filePath)) {             System.out.println("file【" + filePath + "】 not found!");             return null;         }         // HashMap         Map<Integer, Cell[]> hashMap = new HashMap<Integer, Cell[]>();         File file = new File(filePath);         // 工作薄         Workbook wb = Workbook.getWorkbook(file);         // 根据名字获得工作表         Sheet sheet = wb.getSheet(sheetName);         // 判断工作表是否存在         if (!isSheet(wb, sheetName)) {             System.out.println("工作表 【 " + sheetName + "】not found!");             return null;         }         // 获得工作表的总行数、总列数         int rows = getRowNum(sheet);         int columns = getColumnNum(sheet);         // 根据内容定位到单元格         Cell cellKey = sheet.findCell(key);         if (cellKey == null) {             System.out.println("关键字 【 " + key + "】not found!");             return null;         }         // key 坐标         int yKey = cellKey.getColumn();         int xKey = cellKey.getRow();         // 存储数据         Cell[] cells2 = null;         for (int i = 0; i < (rows - xKey); i++) {             cells2 = sheet.getRow(xKey + i);             hashMap.put(i, cells2);         }         // 关闭         wb.close();         return (HashMap<Integer, Cell[]>) hashMap;     }     public static HashMap<Integer, Cell[]> m0(String filePath, String sheetName)             throws BiffException, IOException {         // 判断文件是否有效         if (!isFilePath(filePath)) {             System.out.println("file【" + filePath + "】 not found!");             return null;         }         // HashMap         Map<Integer, Cell[]> hashMap = new HashMap<Integer, Cell[]>();         File file = new File(filePath);         // 工作薄         Workbook wb = Workbook.getWorkbook(file);         // 根据名字获得工作表         Sheet sheet = wb.getSheet(sheetName);         // 判断工作表名称是否正确         if (!isSheet(wb, sheetName)) {             System.out.println("工作表 【 " + sheetName + "】not found!");             return null;         }         // 获得工作表的总行数、总列数         int rows = getRowNum(sheet);         int columns = getColumnNum(sheet);         // 存储数据         Cell[] cells2 = null;         for (int i = 0; i < rows; i++) {             cells2 = sheet.getRow(i);             hashMap.put(i, cells2);         }         wb.close();         return (HashMap<Integer, Cell[]>) hashMap;     }     public static boolean isFilePath(String filePath) {         if (new File(filePath).isFile()) {             return true;         }         return false;     }     public static boolean isSheet(Workbook wb, String sheetName) {         if (wb.getSheet(sheetName) != null) {             return true;         }         return false;     }     public static int getRowNum(Sheet st) {         if (st == null) {             return 0;         }         return st.getRows();     }     public static int getColumnNum(Sheet st) {         if (st == null) {             return 0;         }         return st.getColumns();     } }

分离页面操作05-DataProvider提供测试数据

5.类DataProvider-提供测试数据 使用到的类:HashMapExcel HashMapExcel-读取数据驱动文件excel中内容,并转为二维数组 package com.app.dataProvider; import java.io.IOException; import java.util.HashMap; import jxl.Cell; import jxl.read.biff.BiffException; import org.testng.annotations.DataProvider; public class DataProviderTest {   // DataProvider如果与测试类不在同一个类中,则需要static修饰方法,excel中     private static HashMap hm = new HashMap();     @DataProvider(name = "loginDataProvider")     public static Object[][] data2() throws BiffException, IOException {         hm = HashMapExcel.m0("./excel/parameters.xls", "login", "userName");         if(hm == null){             return null;         }         return HashMapExcel.getData(hm);     } }

分离页面操作06-测试

6.测试 使用到的类:ElementAction package com.test; import static org.testng.Assert.*; import org.openqa.selenium.WebElement; import org.testng.annotations.Test; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; import com.app.pageobjects.ElementAction; public class Tester {     private ElementAction elementAction;     @Test(groups="login")     public void f0() {         elementAction.load();         assertEquals(elementAction.getBaseUrl(),                 elementAction.driver.getCurrentUrl());     }     @Test(dependsOnMethods = "f0",groups="login")     public void f1() {         elementAction.login();     }     @Test(dependsOnMethods = "f1", dataProvider = "test0", dataProviderClass = com.app.dataProvider.DataProviderTest.class)     public void f2(String name, String pass) throws InterruptedException {         elementAction.loginFailure(name, pass);         // 断言 登录失败         WebElement loginDivError = elementAction.pageElement.getLoginDivError();         if (name.trim().equals(""))             assertEquals("请输入登录名", loginDivError.getText());         else if (pass.equals(""))             assertEquals("请输入密码", loginDivError.getText());         else             assertEquals("登录名或密码错误", loginDivError.getText());         Thread.sleep(3000);     }     @Test(dependsOnMethods = "f1",groups="login")     public void f3() throws InterruptedException {         elementAction.loginSuccess();         assertEquals("发博文", elementAction.pageElement.getSgPublish().getText());     }     @BeforeSuite     public void beforeSuite() {         elementAction = ElementAction.getInstance("ff");     }     @AfterSuite     public void afterSuite() {         // blogPageService.close();     } }

转载于:https://www.cnblogs.com/stay-sober/p/4158850.html

最新回复(0)