Let’s start investigating this topic with a HomePage implemented using Page Factory:
public class HomePage {
private WebDriver driver;
private static final String HOME_PAGE_URL = "https://www.vpl.ca/";
@FindBy(id = "edit-search")
private WebElement searchBox;
@FindBy(id = "edit-submit")
private WebElement searchButton;
public HomePage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.driver = driver;
}
public void open() {
driver.get(HOME_PAGE_URL);
}
public boolean isDisplayed() {
return getUrl().equalsIgnoreCase(HOME_PAGE_URL);
}
private String getUrl() {
return driver.getCurrentUrl();
}
public ResultsPage searchBy(String keyword) {
typeKeyword(keyword);
clickSearchButton();
return new ResultsPage(driver);
}
private void typeKeyword(String keyword) {
searchBox.sendKeys(keyword);
}
private void clickSearchButton() {
searchButton.click();
}
}
The class has 43 lines of code.
Let’s rewrite it using the Page Object Model:
public class HomePage {
private WebDriver driver;
private static final String HOME_PAGE_URL = "https://www.vpl.ca/";
private By searchBoxId = By.id("edit-search");
private By searchButtonId = By.id("edit-submit");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public void open() {
driver.get(HOME_PAGE_URL);
}
public boolean isDisplayed() {
return getUrl().equalsIgnoreCase(HOME_PAGE_URL);
}
private String getUrl() {
return driver.getCurrentUrl();
}
public ResultsPage searchBy(String keyword) {
typeKeyword(keyword);
clickSearchButton();
return new ResultsPage(driver);
}
private void typeKeyword(String keyword) {
WebElement searchBox = driver.findElement(searchBoxId);
searchBox.sendKeys(keyword);
}
private void clickSearchButton() {
WebElement searchButton = driver.findElement(searchButtonId);
searchButton.click();
}
}
41 lines of code.
Less than 43.
Can we do better with Page Object Model?
Sure, we can.
public class HomePage {
private WebDriver driver;
private static final String HOME_PAGE_URL = "https://www.vpl.ca/";
private By searchBoxId = By.id("edit-search");
private By searchButtonId = By.id("edit-submit");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public void open() {
driver.get(HOME_PAGE_URL);
}
public boolean isDisplayed() {
return getUrl().equalsIgnoreCase(HOME_PAGE_URL);
}
public String getUrl() {
return driver.getCurrentUrl();
}
public ResultsPage searchBy(String keyword) {
typeKeyword(keyword);
clickSearchButton();
return new ResultsPage(driver);
}
private void typeKeyword(String keyword) {
driver.findElement(searchBoxId).sendKeys(keyword);
}
private void clickSearchButton() {
driver.findElement(searchButtonId).click();
}
}
39 lines of code.
Less than 41.
Less than 43.
So, using Page Factory does not necessarily reduce the size of our page classes.
What other issues can this model bring?