Selenium webdriver Java 封装与重用

目的

1. 简化调用

WebDriver对页面的操作,需要找到一个WebElement,然后再对其进行操作,比较繁琐:

WebElement element =driver.findElement(By.name("q")); 
element.sendKeys("Cheese!"); 

 我们可以考虑对这些基本的操作进行一个封装,简化操作。比如,封装代码:

protected void sendKeys(By by, String value){ 
driver.findElement(by).sendKeys(value); 
} 

 那么,在测试用例可以这样调用:

sendKeys(By.name("q"),”Cheese!”);
2. 添加异常捕获或等待

对于一些常用的操作,比如查找元素,我们可以在查找元素前面添加一个显性等待,然后再是查找元素。

protected void findEle(By by){ 
new WebDriverWait(driver,10).until(    ExpectedConditions.presenceOfElementLocated(by));
return driver.findElement(by); 
} 

样例

封装之后,我们可以把这些封装函数放到公共模块,方便调用。

更普遍的方式是作为BasePage的方法,在POM方式中,其他所有Page都继承自 BasePage,这样所有的Page都可以直接调用这些方法。

比如下面的简单的 BasePage :

import java.util.List;  
import java.util.NoSuchElementException;  
import java.util.concurrent.TimeUnit;  
import org.openqa.selenium.By;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class BasePage{ protected RemoteWebDriver driver; protected WebDriverWait driverWait; private int WAIT_ELEMENT_TO_LOAD=10; protected boolean isWebElementExist(By selector) { try { driver.findElement(selector); return true; } catch(NoSuchElementException e) { return false; } } protected String getWebText(By by) { try { return driver.findElement(by).getText(); } catch (NoSuchElementException e) { return "Text not existed!"; } } protected void clickElementContainingText(By by, String text){ List<WebElement>elementList = driver.findElements(by); for(WebElement e:elementList){ if(e.getText().contains(text)){ e.click(); break; } } } protected String getLinkUrlContainingText(By by, String text){ List<WebElement>subscribeButton = driver.findElements(by); String url = null; for(WebElement e:subscribeButton){ if(e.getText().contains(text)){ url =e.getAttribute("href"); break; } } return url; } protected void click(By by){ driver.findElement(by).click(); driver.manage().timeouts().implicitlyWait(WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS); } protected String getLinkUrl(By by){ return driver.findElement(by).getAttribute("href"); } protected void sendKeys(By by, String value){ driver.findElement(by).sendKeys(value); } 
}

转载于:https://www.cnblogs.com/miniren/p/4638935.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值