A Page Object is an abstract representation of a web page that includes its elements and its attributes; through a Page Object, we can perform automation scripts that follow the POM approach.
The following steps describe how to create a Page Object:
- Create a new Java file by using your IDE of choice.
- Define a package for your Object Repository and include it at the top of every Page Object file that you create, as follows:
package com.beginningselenium.examples.pageobjects;
- Since we are creating a Page Object for the Age Calculator application, it might be a good idea to name our class AgeCalculatorPage, as shown here:
public class AgeCalculatorPage {
}
- Our AgeCalculatorPage class must include all WebElements of the web page that we might use in the automation script. We can include them as follows (it is a good practice to use the same names or IDs that are given to the names in the web page):
private WebElement dayOfBirth;
private WebElement age;
- Set variables and methods to handle the driver, as follows:
private WebDriver driver;
private String url = "https://trainingbypackt.github.io/
Beginning-Selenium/lesson_6/exercise_6_1.html";
public void open() {
this.driver.get(url);
}
public void close() {
this.driver.quit();
}
- Write a constructor to the AgeCalculatorPage class that maps the elements of the page to the variables of the class, as follows:
public AgeCalculatorPage(WebDriver webDriver) {
driver = webDriver;
}
- Write operations to read the values of the required WebElements:
public String getAge() {
age = driver.findElement(By.id("age"));
return age.getAttribute("value");
}
- Our Age Calculator application includes a button that calculates the age and the zodiac sign of the user. We can also model this by using Page Object Model:
public void calculate(String day, String month, String
year) {
getDayOfBirth().sendKeys(day);
getMonthOfBirth().sendKeys(month);
getYearOfBirth().sendKeys(year);
getCalculate().click();
}
You should now understand how to implement a Page Object for a web page.