Simple Selenium Test Automation Project in Java with Page Object Model

How to optimize your tests using the Page Object Model.

Image for post
Image for post
Photo by John Barkiple on Unsplash

What is PageObject?

Page Object Model is an object design pattern, in which for every web page in the application, there should be a relevant page class, various elements on the page are defined as variables on the class. To interact with different elements of web page methods are implemented in the class.

public class HomePage {

//Variables
@FindBy(xpath = "xpath")
private WebElement signInButton;
@FindBy(xpath = "xpath")
private WebElement userAvatar;
//Methods
public void clickSignInButton() {
signInButton.click();
}
  • Due to well-named methods in classes, code is easy to read and to maintain.
  • Tests are more concise because we are using existing methods of page object classes.
  • Any changes in the webpage can easily be implemented, in one place, that is in our Page Object Class.

Getting Ready

To create a Page Object Model of our website, first of all, we create a class in our automation framework to represent the corresponding page of our application.

public class HomePage{
}
By signinButton = By.xpath("//a[@class='HeaderMenu-link no-underline mr-3']");
public void clickSigninButton();
public void signIn(String usersEmail, String password);
public void signIn(String usersEmail, String password) {
setUserEmail(usersEmail);
setUserPassword(password);
clikOnSubmit();
}
By signinButton = By.xpath("//a[@class='HeaderMenu-link no-underline mr-3']");public void clickSignInButton() {
driver.findElement(signInButton).click();
}
@FindBy(xpath = "//a[@class='HeaderMenu-link no-underline mr-3']")
private WebElement signInButton;
LoginPage page = PageFactory.intElements(driver,LoginPage.class)
public LoginPage(WebDriver driver) {           
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void checkCheckbox(){
if(!checkBox.isSelected){
checkBox.click
}
}

Simple Selenium Test Automation Project in Java

For the purpose of our Page Object Model tutorial, let’s automate sign in for GitHub. To do that, we need to automate the following steps:

Setting Up the Project

To separate the logic of tests and our page object classes we will put them in different folders.

Homepage

SignIn Page

Running Tests

Now to check whether sign-in functionality works correctly on GitHub we will write a few unit tests.

public void signIn(String usersEmail, String password) {
if (isPageOpened()) {
setUserEmail(usersEmail);
setUserPassword(password);
clickOnSubmit();
}
}

Conclusion

Page Object Model and Page Factory make it easy to model web pages in Selenium and test them automatically.

Written by

QA and free artist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store