Webdriver中PageFactory的正确用法
以博客园登录、退出为例:
下面是LoginPage的源码:
public class LoginPage {
private WebDriver driver;
@FindBy(how = How.ID, id = "input1")
private WebElement userName;
@FindBy(how = How.ID, id = "input2")
private WebElement passWord;
@FindBy(how = How.ID, id = "signin")
private WebElement loginButton;
public LoginPage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver,this); PageFactory.initElements一般放在自己的构造函数中,这样别的类调用的时候能保证每次都调用成功。
}
public void login(String username, String password)
{
userName.clear();
passWord.clear();
userName.sendKeys(username);
passWord.sendKeys(password);
loginButton.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
}
下面是Mainpage的代码:
public class MainPage {
private WebDriver driver;
@FindBy(how = How.LINK_TEXT, linkText = "登录")
WebElement loginLink;
@FindBy(how = How.LINK_TEXT, linkText = "退出")
WebElement logoutLink;
public MainPage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver,this);
}
public void openMainPage(String url)
{
driver.get(url);
//loginLink = driver.findElement(By.linkText("登录"));
//logoutLink = driver.findElement(By.linkText("退出"));
}
public void login(String userName, String passWord)
{
loginLink.click();
WebDriverWait wait = new WebDriverWait(driver,300);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("input1")));
LoginPage loginPage = new LoginPage(driver);
loginPage.login(userName,passWord);
}
public void logout()
{
logoutLink.click();
LogoutPage logoutPage = new LogoutPage(driver);
logoutPage.logout();
}
}
下面是测试用的TestPage的代码:
public class TestPage {
WebDriver driver;
@BeforeTest
public void setUp()
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "allow-running-insecure-content", "--test-type");
options.addArguments("--user-data-dir="+System.getenv("USERPROFILE")+"/AppData/Local/Google/Chrome/User Data/Default");
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe"); //先设置这个
driver = new ChromeDriver(options);//再选择浏览器
}
@Test
public void testMainPage() throws Exception
{
//MainPage mainPage = PageFactory.initElements(driver,MainPage.class);
MainPage mainPage =new MainPage(driver); 有些人把PageFactory放在这里调用,其实是不合理的,这样容易漏掉LoginPage里的PageFactory
mainPage.openMainPage("http://www.cnblogs.com");
mainPage.login("WebdriverTest","Password123!");
mainPage.logout();
}
}