Page objects are one of the simplest ways to organise your test automation code. The basic principle is to have a class that represents each of your pages. You then create methods to take the actions that a user would.
Without some way of logically organising your code, it soon becomes impossible to maintain. The Page Object Model allows you to know where code should exist. Code for logging a user in? It should exist in a LoginPage class. Code for registering a user? It should exist in a RegistrationPage class.
If we take a look at the following login form, we can see the elements (parts of the page) that the user needs to interact with to log in.
- The email address field
- The password field
- The keep me logged in checkbox
- The login button
So now that we know some of the things we’ll need to interact with on the page, let’s think about method naming. The naming of your methods is important. Well named methods will make it clear what your code is doing at a glance.
For the above interactions, we can make the following methods:
- fillEmailAddressField
- fillPasswordField
- tickKeepMeLoggedIn
- clickLoginButton
Notice how each of the methods we are going to create have logical names that say exactly what they’ll be doing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LoginPage { | |
private WebDriver driver; | |
public LoginPage(WebDriver driver) { | |
this.driver = driver; | |
} | |
public void fillEmailAddressField(String text) { | |
driver.findElement(By.id("emailAddress")).sendKeys(text); | |
} | |
public void fillPasswordField(String text) { | |
driver.findElement(By.id("password")).sendKeys(text); | |
} | |
public void tickKeepMeLoggedIn() { | |
driver.findElement(By.id("keepMeLoggedIn")).click(); | |
} | |
public void clickLoginButton() { | |
driver.findElement(By.id("loginBtn")).click(); | |
} | |
} |
In the code above the constructor has a parameter that allows us to pass in our WebDriver instance. There’s a few ways of going about managing the use of a single instance of WebDriver in your page objects, but this is my preferred method.
This is a very basic implementation of a Page Object Model, and I would recommend reading more posts on this and other sites in order to pick up some other good practices for using the Page Object Model, and WebDriver in general.