WebDriver对象管理之PageObject与PageFactory对比

 
在之前的<a href="http://www.jianshu.com/p/71e04066be61">自动化框架搭建</a>文章中有提到过对象管理(或元素管理),而WebDriver给我们提供了两种对象管理思路PageObject与PageFactory,今天我就对比下两种方式的异同~


关于PageObject
将一个页面或一类元素看做是一个页面对象,一个页面对象对应一个类,将元素对象的获取定义在这一个类中。(解释总显得那么苍白,看代码吧)
方式一:

方式二:

 

方式一直接返回findElement()方法,遇到元素未定位到等情况会抛出NoSuchElementException 异常,从而中断测试,所以我这边给出了方式二(推荐方式二),这里给出isElementExist()方法:

关于PageFactory
整体思想同PageObject,只是在表现形式上通过注解(@FindBy)的方式定义元素对象,看代码:****
方式一:

使用对象的时候需要先初始化类:

 

public class HomePage extends BasePage{
public HomePage(WebDriver driver) {
super(driver);
}
public HomePage(WebDriver driver, String titile) {
super(driver, titile);
}
@FindBy(xpath = "//span[@class='name']")
@CacheLookup
public WebElement userName;

@FindBy(xpath = "//a")
@CacheLookup
public List<WebElement> links;

@FindBy(xpath = "//a[contains(text(),'首页')]")
@CacheLookup
public WebElement homeLink;
}

public class BasePage {
public static final String MAIN_TITLE = "XXX平台";
public WebDriver driver;
public String title;
private final int TIMEOUT = 10;

public BasePage() {}

public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TIMEOUT) , this);
}

public BasePage(WebDriver driver, final String title) {
this.driver = driver;
this.title = title;
try{
new WebDriverWait(driver,TIMEOUT).until(new ExpectedCondition<Boolean>(){
@Override
public Boolean apply(WebDriver arg0) {
// TODO Auto-generated method stub
String acttitle = arg0.getTitle();
return acttitle.equals(title);
}});
}catch(TimeoutException te) {
throw new IllegalStateException("当前页面title(" + driver.getTitle() + ")与预期("+ title +")不一致");
}
PageFactory.initElements(new AjaxElementLocatorFactory(driver, TIMEOUT) , this);
}
}
方式二(推荐使用)增加了页面和元素等待时间,比方式一更加健壮,使用对象时也更加清晰:
总结
上面通过代码的形式给出了PageObject与PageFactory的区别,并且通过代码优化的方式给出了两种对象管理思路推荐的使用方式,两种方式我平时都有使用,有时候还混着用,总体来说并不能说谁好谁坏,各有千秋,看个人的习惯,在元素判断上我觉得PageObject方便一些,元素不存在就是null,这个思路很直接;PageFactory的好处除了使用注解使代码更整洁之外,还可以设置页面和元素加载等待时间,总体来说,还是推荐PageFactory。



 

猜你喜欢

转载自www.cnblogs.com/KatherinaSu/p/9430039.html