Java - 頁面類的最佳實踐
用例:登入 FB 帳戶
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class FaceBookLoginTest {
private static WebDriver driver;
HomePage homePage;
LoginPage loginPage;
@BeforeClass
public void openFBPage(){
driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
loginPage = new LoginPage(driver);
}
@Test
public void loginToFB(){
loginPage.enterUserName("username");
loginPage.enterPassword("password");
homePage = loginPage.clickLogin();
System.out.println(homePage.getUserName());
}
}
頁面類:登入頁面和主頁登入頁面類:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver driver){
this.driver = driver;
}
@FindBy(id="email")
private WebElement loginTextBox;
@FindBy(id="pass")
private WebElement passwordTextBox;
@FindBy(xpath = ".//input[@data-testid='royal_login_button']")
private WebElement loginBtn;
public void enterUserName(String userName){
if(loginTextBox.isDisplayed()) {
loginTextBox.clear();
loginTextBox.sendKeys(userName);
}
else{
System.out.println("Element is not loaded");
}
}
public void enterPassword(String password){
if(passwordTextBox.isDisplayed()) {
passwordTextBox.clear();
passwordTextBox.sendKeys(password);
}
else{
System.out.println("Element is not loaded");
}
}
public HomePage clickLogin(){
if(loginBtn.isDisplayed()) {
loginBtn.click();
}
return new HomePage(driver);
}
}
主頁類:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class HomePage {
WebDriver driver;
public HomePage(WebDriver driver){
this.driver = driver;
}
@FindBy(xpath=".//a[@data-testid='blue_bar_profile_link']/span")
private WebElement userName;
public String getUserName(){
if(userName.isDisplayed()) {
return userName.getText();
}
else {
return "Username is not present";
}
}
}