Selenium + Java · Lesson 6 of 44

0/44 done

Module 6: Object-Oriented Programming

6. Object-Oriented Design for Automation & Page Objects

16 minlesson

Try it yourself

Create a TestUser class:

  1. Private fields: username (String) and role (String).
  2. Constructor accepting username and role.
  3. Getters getUsername() and getRole().
  4. Method isAdmin() returning true if role equals "ADMIN".

The editor has a worked example. Read it, tweak it, then press Mark as complete.

OOP in Test Frameworks

java
// Base Page with encapsulated driver/page reference:
public abstract class BasePage {
    protected String pageUrl;

    public BasePage(String pageUrl) {
        this.pageUrl = pageUrl;
    }

    public void open() {
        System.out.println("Navigating to: " + this.pageUrl);
    }
}

// Child Page inheriting common capabilities:
public class LoginPage extends BasePage {
    private String usernameSelector = "#username";

    public LoginPage() {
        super("https://targetqa.com/login");
    }

    public void login(String user, String pass) {
        open();
        System.out.println("Typing credentials into " + usernameSelector);
    }
}

Key Takeaways & Walkthrough Summary

Object-Oriented Programming is the foundational architecture of the Page Object Model. In this lesson, we explore classes, encapsulation, inheritance with extends and super, and polymorphism tailored specifically for test automation. Let's design scalable classes!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why should locators be private in a Page Object class?

Encapsulation ensures tests interact through business actions (e.g. login()) rather than directly manipulating raw locator strings.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

Java
Skip