举例:博客园的登陆页面:
非PageFactory 和@FindBy的代码如下
public class LoginPage1 {
//定义三个WebElement属性,用于记录用户名、密码、登陆按钮这三个页面元素
WebDriver driver;
WebElement username;
WebElement password;
WebElement loginbutton;
public LoginPage1(WebDriver driver){
this.driver = driver;
username = driver.findElement(By.id("input1"));
password = driver.findElement(By.id("input2"));
loginbutton = driver.findElement(By.id("signin"));
}
//定义一个login()方法,用于发送用户名和密码并登陆网站
public void login(String userName,String passWord){
username.sendKeys(userName);
password.sendKeys(passWord);
loginbutton.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
}
PageFactory 和@FindBy的代码如下
public class LoginPage2 {
WebDriver driver;
//在页面中的任意一个页面元素都可以使用@FindBy注解来进行标记。
//@FindBy可用于替换drive.findElement()方法的查找机制来定位页面元素
@FindBy(how = How.ID,id = "input1")
WebElement username;
@FindBy(how = How.ID,id="input2")
WebElement password;
@FindBy(how = How.ID,id="signin")
WebElement loginbutton;
public LoginPage2(WebDriver driver){
this.driver = driver;
}
public void login(String userName,String passWord){
username.sendKeys(userName);
password.sendKeys(passWord);
loginbutton.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
}
相比而言:使用了@FindBy注解模式的代码更清晰,在构造函数里面的@FindBy(how = How.ID,id = "xx")代替了一系列driver.findElement(By.id("xx"));
举例 发送消息
非PageFactor工厂模式
public void sendMessage(String toUser,String titleConent,String textConent){
enterMessageBox();
newMessage = driver.findElement(By.linkText("撰写新短信"));
newMessage.click();
SendMessagePage1 sendMessagePage = new SendMessagePage1(driver);
sendMessagePage.sendNewMessage(toUser, titleConent, textConent);
}
PageFactor工厂模式
public void sendMessage(String toUser,String titleContent,String textConten){
enterMessageBox();
newMessage.click();
SendMessagePage2 sendMessagePage = PageFactory.initElements(driver, SendMessagePage2.class);
sendMessagePage.sendNewMessage(toUser, titleContent, textConten);
}
相比而言:使用了PageFactor工厂模式的代码更清晰, PageFactory.initElements(driver, SendMessagePage2.class)代替了new SendMessagePage1(driver);实例化