Page Factory Pattern

In the previous example, though we have abstracted the locators, we still keep repeating the part of driver.findElement while working with elements.

The PageFactory pattern allows you to get rid of that as well.This helps a lot in making the code look more clean and readable.

Let's look at the code first and then we talk about it later.

public class SignupPage {

WebDriver driver;


@FindBy(id = "user_first_name")
private WebElement firstNameTextBox;

@FindBy(id = "user_last_name")
private WebElement lastNameTextBox;

@FindBy(id = "user_email")
private WebElement emailTextBox;

@FindBy(id = "user_password")
private WebElement passwordTextBox;

@FindBy(id = "user_password_confirmation")
private WebElement confirmPasswordTextBox;

@FindBy(name = "commit")
private WebElement signupButton;


public SignupPage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
}

public void she_provides_the_first_name_as(String firstName) throws Throwable {
    firstNameTextBox.sendKeys(firstName);
}


public void she_provides_the_last_name_as(String lastName) throws Throwable {
    lastNameTextBox.sendKeys(lastName);
}

public void she_provides_the_email_as(String email) throws Throwable {
    emailTextBox.sendKeys(email);
}

public void she_provides_the_password_as(String password) throws Throwable {
    passwordTextBox.sendKeys(password);
}

public void she_provides_the_confirm_password_again_as(String confirmPassword) throws Throwable {
    confirmPasswordTextBox.sendKeys(confirmPassword);
}


public void she_signs_up() throws Throwable {
    signupButton.click();
}

}

Now that you have seen the code lets understand the chnaged pieces on by one.

  • @FindBy annotation - The annotation can take the locator strategy as paramters and when the code tries to use the webelement in the method, this is used to find the element.
  • WebElements as variables - Another thing you notice is that we are directly defining the Webelements as variables. This is what "driver.findElement" call was returning. This helps to directly access the element and perform actions on it.

We can do the same for the other 2 page classes.

results matching ""

    No results matching ""