Page Methods in Selenium Page Object Model (POM)
Page Methods are methods defined inside Page Object classes to represent the actions, operations, and services that a user can perform on a particular web page. In Selenium automation, Page Methods are an important part of the Page Object Model because they keep Selenium interaction logic inside page classes instead of placing locators and WebDriver commands directly inside test cases.
For example, instead of writing driver.findElement(By.id("username")).sendKeys("admin") repeatedly in different test classes, a LoginPage can provide a method such as enterUsername(). The test can then simply call loginPage.enterUsername("admin").
This approach separates test logic from page interaction logic, reduces duplicate code, improves readability, and makes UI changes easier to maintain. Selenium's official documentation describes Page Objects as an abstraction that models the services offered by a page and keeps page-specific implementation details in one place.
Course Resource: Selenium Training | Register for Course Demo
1. What are Page Methods?
Page Methods are reusable Java methods created inside Page Object classes. Each method normally represents one meaningful action or operation available on a web page.
For example, a Login Page may contain methods such as:
enterUsername()
enterPassword()
clickLogin()
loginAs()
getErrorMessage()
These methods hide the Selenium implementation details from the test class.
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
loginPage.enterPassword("admin123");
loginPage.clickLogin();
The test focuses on what action needs to be performed, while the Page Object handles how the action is performed.
2. Why are Page Methods Important?
Page Methods are important because automation frameworks often contain hundreds or thousands of Selenium interactions. If those interactions are directly written in test classes, the framework becomes difficult to maintain.
- Reduce duplicate Selenium code.
- Centralize page-specific operations.
- Improve test readability.
- Improve code reusability.
- Separate test logic from UI interaction logic.
- Make UI changes easier to manage.
- Support scalable automation frameworks.
- Make tests easier for other team members to understand.
- Encourage object-oriented automation design.
- Allow page workflows to be reused across multiple tests.
3. Page Method Architecture
Test Class
|
v
Page Method
|
v
Page Locator
|
v
Selenium WebDriver
|
v
Web Browser
|
v
Application
The test class calls a page method. The page method uses the appropriate locator and WebDriver operation to interact with the application.
4. Page Methods and POM
Page Methods are one of the core implementation elements of the Page Object Model. A Page Object generally contains the locators and methods required to interact with a particular page or reusable component.
LoginPage.java
|
+-- Locators
| +-- username
| +-- password
| +-- loginButton
|
+-- Page Methods
+-- enterUsername()
+-- enterPassword()
+-- clickLogin()
+-- loginAs()
The test class does not need to know the locator details.
5. Page Method vs Test Method
| Page Method | Test Method |
| Belongs to a Page Object | Belongs to a test class |
| Handles page interaction | Validates application behavior |
| Contains Selenium operations | Calls Page Methods |
| Usually reusable | Represents a test scenario |
| Focuses on application services | Focuses on expected behavior |
| Should generally avoid test assertions | Normally contains assertions |
6. Simple Page Method Example
public class LoginPage {
WebDriver driver;
By username = By.id("username");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(username).sendKeys(value);
}
}
The test can use the method like this:
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
7. Creating a Login Page Class
A Login Page commonly contains username, password, and login-button locators along with methods representing login operations.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By loginButton = By.id("loginButton");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String username) {
driver.findElement(usernameField).sendKeys(username);
}
public void enterPassword(String password) {
driver.findElement(passwordField).sendKeys(password);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}
8. Calling Page Methods from Test Class
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void validLoginTest() {
LoginPage loginPage = new LoginPage(driver);
loginPage.enterUsername("admin");
loginPage.enterPassword("admin123");
loginPage.clickLogin();
}
}
The test class is now easier to read because the Selenium implementation is encapsulated inside the Page Object.
9. Method for Entering Username
A dedicated method can represent the action of entering a username.
public void enterUsername(String username) {
driver.findElement(usernameField)
.clear();
driver.findElement(usernameField)
.sendKeys(username);
}
The clear() operation is useful when the field may already contain text.
10. Method for Entering Password
public void enterPassword(String password) {
driver.findElement(passwordField)
.clear();
driver.findElement(passwordField)
.sendKeys(password);
}
Keeping the password interaction in the Page Object prevents the locator and WebDriver code from being duplicated across tests.
11. Method for Clicking Login
public void clickLogin() {
driver.findElement(loginButton)
.click();
}
The test can simply call:
loginPage.clickLogin();
12. Creating a Complete Login Method
Individual actions can be combined into a higher-level workflow method.
public void login(String username, String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
}
The test becomes:
LoginPage loginPage = new LoginPage(driver);
loginPage.login("admin", "admin123");
This is usually more expressive than exposing every low-level interaction to the test.
13. Low-Level vs High-Level Page Methods
| Type | Example | Purpose |
| Low-Level | enterUsername() | Performs one UI action |
| Low-Level | clickLogin() | Clicks one element |
| High-Level | login() | Performs complete login workflow |
| High-Level | searchProduct() | Performs complete search operation |
| High-Level | checkoutProduct() | Performs checkout workflow |
14. Returning void from Page Methods
A Page Method can return void when the action does not need to provide a result to the caller.
public void clickLogin() {
driver.findElement(loginButton).click();
}
This is appropriate for simple actions where the test does not need another object or value from the method.
15. Returning String from Page Methods
A Page Method can return information obtained from the page.
private By errorMessage = By.id("error");
public String getErrorMessage() {
return driver.findElement(errorMessage)
.getText();
}
The test can then validate the returned value.
String actualMessage = loginPage.getErrorMessage();
Assert.assertEquals(
actualMessage,
"Invalid username or password"
);
16. Returning Boolean from Page Methods
Page Methods can return boolean values when the test needs to know whether an element or condition is present.
public boolean isLoginButtonDisplayed() {
return driver.findElement(loginButton)
.isDisplayed();
}
Test:
Assert.assertTrue(
loginPage.isLoginButtonDisplayed()
);
17. Returning WebElement from Page Methods
Although Page Methods can technically return WebElement objects, exposing WebElements to test classes should generally be limited because it can expose page implementation details.
public WebElement getLoginButton() {
return driver.findElement(loginButton);
}
In many cases, it is cleaner to provide a meaningful service method such as clickLogin() instead of returning the WebElement.
18. Returning Another Page Object
When an action navigates to another page, the Page Method can return the corresponding Page Object.
public HomePage clickLogin() {
driver.findElement(loginButton).click();
return new HomePage(driver);
}
The test can then write:
HomePage homePage = loginPage.clickLogin();
This models the application's page-to-page navigation and keeps the test readable.
19. Page Methods for Navigation
Navigation methods can represent actions that move the user from one page to another.
public HomePage clickHome() {
driver.findElement(homeLink).click();
return new HomePage(driver);
}
public CartPage openCart() {
driver.findElement(cartLink).click();
return new CartPage(driver);
}
Test:
HomePage homePage = loginPage.clickHome();
CartPage cartPage = homePage.openCart();
20. Page Methods for Search
public SearchResultsPage searchProduct(String product) {
driver.findElement(searchBox)
.clear();
driver.findElement(searchBox)
.sendKeys(product);
driver.findElement(searchButton)
.click();
return new SearchResultsPage(driver);
}
The test becomes:
SearchResultsPage results =
homePage.searchProduct("Laptop");
21. Page Methods for Dropdowns
Page Methods can encapsulate dropdown interaction.
private By countryDropdown =
By.id("country");
public void selectCountry(String country) {
Select select =
new Select(driver.findElement(countryDropdown));
select.selectByVisibleText(country);
}
Test:
registrationPage.selectCountry("India");
22. Page Methods for Checkboxes
private By termsCheckbox =
By.id("terms");
public void acceptTerms() {
WebElement checkbox =
driver.findElement(termsCheckbox);
if (!checkbox.isSelected()) {
checkbox.click();
}
}
The method represents the business action rather than exposing the checkbox implementation.
23. Page Methods for Radio Buttons
private By maleRadio =
By.id("male");
public void selectMaleGender() {
driver.findElement(maleRadio).click();
}
For reusable frameworks, a parameterized method can also be created:
public void selectGender(String gender) {
if (gender.equalsIgnoreCase("male")) {
driver.findElement(By.id("male")).click();
} else if (gender.equalsIgnoreCase("female")) {
driver.findElement(By.id("female")).click();
}
}
24. Page Methods for Forms
A complete form can be represented using multiple smaller Page Methods or one high-level method.
public void enterName(String name) {
driver.findElement(nameField).sendKeys(name);
}
public void enterEmail(String email) {
driver.findElement(emailField).sendKeys(email);
}
public void enterMobile(String mobile) {
driver.findElement(mobileField).sendKeys(mobile);
}
public void submitForm() {
driver.findElement(submitButton).click();
}
A high-level method can combine them:
public void register(
String name,
String email,
String mobile) {
enterName(name);
enterEmail(email);
enterMobile(mobile);
submitForm();
}
25. Page Methods with Parameters
Parameters make Page Methods reusable with different values.
public void search(String keyword) {
driver.findElement(searchBox)
.clear();
driver.findElement(searchBox)
.sendKeys(keyword);
driver.findElement(searchButton)
.click();
}
The same method can be used for multiple products:
searchPage.search("Laptop");
searchPage.search("Mobile");
searchPage.search("Headphones");
26. Page Methods with Multiple Parameters
public void login(
String username,
String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
}
Multiple parameters are useful when an operation logically requires multiple inputs.
27. Page Methods and Data Providers
Page Methods work effectively with TestNG Data Providers. The Data Provider supplies different input values while the Page Method performs the same UI operation.
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"admin", "admin123"},
{"manager", "manager123"},
{"employee", "employee123"}
};
}
@Test(dataProvider = "loginData")
public void loginTest(
String username,
String password) {
loginPage.login(username, password);
}
28. Page Methods and Assertions
Page Objects should generally provide information or services, while test classes perform the assertions about expected application behavior.
public String getPageTitle() {
return driver.getTitle();
}
Test class:
String actualTitle =
homePage.getPageTitle();
Assert.assertEquals(
actualTitle,
"Dashboard"
);
This keeps verification logic in the test rather than embedding test expectations inside the Page Object.
29. Page Method for Error Messages
private By errorMessage =
By.cssSelector(".error-message");
public String getErrorMessage() {
return driver.findElement(errorMessage)
.getText();
}
Test:
Assert.assertEquals(
loginPage.getErrorMessage(),
"Invalid credentials"
);
30. Page Method for Page Title
public String getPageTitle() {
return driver.getTitle();
}
Test:
Assert.assertEquals(
homePage.getPageTitle(),
"Home Page"
);
31. Page Method for URL
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
Test:
Assert.assertTrue(
homePage.getCurrentUrl()
.contains("/dashboard")
);
32. Page Methods for Element State
Page Methods can expose meaningful state information.
public boolean isLogoutButtonVisible() {
return driver.findElement(logoutButton)
.isDisplayed();
}
public boolean isLoginButtonEnabled() {
return driver.findElement(loginButton)
.isEnabled();
}
33. Page Methods with Explicit Wait
When an operation depends on an element becoming available, a Page Method can encapsulate an explicit wait.
private WebDriverWait wait;
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
}
public void clickLogin() {
WebElement button =
wait.until(
ExpectedConditions.elementToBeClickable(
loginButton
)
);
button.click();
}
This keeps synchronization logic close to the page element it belongs to.
34. Page Methods for Dynamic Elements
Dynamic pages often require methods that locate elements at runtime.
public void selectProduct(String productName) {
By product =
By.xpath(
"//div[@class='product' and normalize-space()='" +
productName +
"']"
);
driver.findElement(product).click();
}
The test can use:
productPage.selectProduct("Laptop");
35. Page Methods for Tables
Page Methods can encapsulate operations performed on tables.
public boolean isUserPresent(String username) {
List<WebElement> rows =
driver.findElements(
By.cssSelector("table tbody tr")
);
for (WebElement row : rows) {
if (row.getText()
.contains(username)) {
return true;
}
}
return false;
}
The test only needs to ask whether the user is present.
36. Page Methods for E-Commerce Cart
public void addProductToCart(String productName) {
By addButton = By.xpath(
"//div[contains(@class,'product')]" +
"[.//h3[normalize-space()='" +
productName +
"']]//button"
);
driver.findElement(addButton).click();
}
Test:
productPage.addProductToCart("Laptop");
productPage.addProductToCart("Mouse");
37. Page Methods for Checkout
public void enterShippingDetails(
String name,
String address,
String city,
String postalCode) {
driver.findElement(nameField)
.sendKeys(name);
driver.findElement(addressField)
.sendKeys(address);
driver.findElement(cityField)
.sendKeys(city);
driver.findElement(postalCodeField)
.sendKeys(postalCode);
}
This method groups logically related actions into one reusable service.
38. Method Chaining in Page Objects
Page Methods can return this when the action keeps the user on the same page. This allows method chaining.
public LoginPage enterUsername(String username) {
driver.findElement(usernameField)
.sendKeys(username);
return this;
}
public LoginPage enterPassword(String password) {
driver.findElement(passwordField)
.sendKeys(password);
return this;
}
The test can use:
loginPage
.enterUsername("admin")
.enterPassword("admin123");
39. Fluent Login Method
A complete fluent workflow can be created using Page Methods.
public LoginPage enterUsername(String username) {
driver.findElement(usernameField)
.sendKeys(username);
return this;
}
public LoginPage enterPassword(String password) {
driver.findElement(passwordField)
.sendKeys(password);
return this;
}
public HomePage submitLogin() {
driver.findElement(loginButton).click();
return new HomePage(driver);
}
Test:
HomePage homePage =
loginPage
.enterUsername("admin")
.enterPassword("admin123")
.submitLogin();
40. Page Methods for Successful and Failed Actions
The same UI action may have different expected destinations. For example, a successful login may navigate to a Home Page, while an unsuccessful login remains on the Login Page.
public HomePage loginAs(
String username,
String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
return new HomePage(driver);
}
public LoginPage loginExpectingFailure(
String username,
String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
return new LoginPage(driver);
}
41. Page Methods Should Represent User Actions
A good Page Method usually represents something meaningful from the perspective of the user or application.
| Less Meaningful | More Meaningful |
| clickElement() | clickLogin() |
| typeText() | enterUsername() |
| clickButton() | submitRegistration() |
| selectValue() | selectCountry() |
| clickLink() | openShoppingCart() |
Meaningful names make test cases easier to understand.
42. Avoid Exposing Page Internals
A Page Object should hide implementation details wherever practical.
Instead of:
loginPage.getUsernameElement().sendKeys("admin");
loginPage.getPasswordElement().sendKeys("admin123");
loginPage.getLoginButton().click();
Prefer:
loginPage.login("admin", "admin123");
This allows the Page Object to control how the interaction is implemented.
43. Locators Should Stay Inside Page Classes
Page Methods should normally use locators defined within the corresponding Page Object.
public class LoginPage {
private By username =
By.id("username");
private By password =
By.id("password");
private By loginButton =
By.id("loginButton");
public void login(
String user,
String pass) {
driver.findElement(username)
.sendKeys(user);
driver.findElement(password)
.sendKeys(pass);
driver.findElement(loginButton)
.click();
}
}
The test should not need to know the IDs.
44. Page Methods and Maintainability
Suppose the login button changes from:
By.id("loginButton")
to:
By.cssSelector(".login-btn")
If the locator is centralized inside the Page Object, the Page Method can be updated in one place.
private By loginButton =
By.cssSelector(".login-btn");
Tests calling clickLogin() do not need to know about the locator change.
45. Page Methods and Reusability
The same Page Method can be reused across many tests.
@Test
public void adminLogin() {
loginPage.login("admin", "admin123");
}
@Test
public void managerLogin() {
loginPage.login("manager", "manager123");
}
@Test
public void employeeLogin() {
loginPage.login("employee", "employee123");
}
Only the input data changes; the login implementation remains centralized.
46. Page Methods and Page Components
Large applications may contain reusable components such as navigation bars, product cards, menus, filters, and headers. Page Methods can be created for these reusable components as well.
public class NavigationBar {
public void openCart() {
driver.findElement(cartLink).click();
}
public void logout() {
driver.findElement(logoutLink).click();
}
}
Page Objects can compose such reusable components instead of duplicating their methods across multiple pages.
47. Page Methods with Base Page
A Base Page can contain common functionality shared by multiple Page Objects.
public class BasePage {
protected WebDriver driver;
protected WebDriverWait wait;
public BasePage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
}
public String getTitle() {
return driver.getTitle();
}
public String getUrl() {
return driver.getCurrentUrl();
}
}
Individual Page Objects can extend the Base Page.
48. Login Page Extending Base Page
public class LoginPage extends BasePage {
private By username =
By.id("username");
private By password =
By.id("password");
private By loginButton =
By.id("loginButton");
public LoginPage(WebDriver driver) {
super(driver);
}
public void login(
String user,
String pass) {
driver.findElement(username)
.sendKeys(user);
driver.findElement(password)
.sendKeys(pass);
driver.findElement(loginButton)
.click();
}
}
49. Page Methods and Test Readability
Compare a test without Page Methods:
driver.findElement(By.id("username"))
.sendKeys("admin");
driver.findElement(By.id("password"))
.sendKeys("admin123");
driver.findElement(By.id("loginButton"))
.click();
With Page Methods:
loginPage.login(
"admin",
"admin123"
);
The second version communicates the business action more clearly.
50. Page Methods and TestNG
TestNG test methods can call Page Methods to perform application interactions and then use assertions to verify the results.
@Test
public void validLoginTest() {
LoginPage loginPage =
new LoginPage(driver);
HomePage homePage =
loginPage.login(
"admin",
"admin123"
);
Assert.assertEquals(
homePage.getPageTitle(),
"Dashboard"
);
}
51. Page Methods and Data-Driven Testing
Page Methods become especially powerful when combined with TestNG Data Providers.
@DataProvider(name = "users")
public Object[][] users() {
return new Object[][] {
{"admin", "admin123"},
{"manager", "manager123"},
{"employee", "employee123"}
};
}
@Test(dataProvider = "users")
public void loginTest(
String username,
String password) {
loginPage.login(username, password);
}
One Page Method handles all the login combinations.
52. Page Methods and Explicit Waits
Synchronization should be encapsulated where appropriate instead of scattering waits throughout test classes.
public void clickSubmit() {
WebElement element =
wait.until(
ExpectedConditions
.elementToBeClickable(submitButton)
);
element.click();
}
This makes the test cleaner:
registrationPage.clickSubmit();
53. Page Methods and JavaScript
JavaScript execution can be encapsulated inside a Page Method when a specific application interaction requires it.
public void scrollToElement(By locator) {
WebElement element =
driver.findElement(locator);
((JavascriptExecutor) driver)
.executeScript(
"arguments[0].scrollIntoView(true);",
element
);
}
However, normal Selenium interactions should generally be preferred when they work correctly.
54. Page Methods for Alerts
public void acceptAlert() {
wait.until(
ExpectedConditions.alertIsPresent()
);
driver.switchTo()
.alert()
.accept();
}
The test can simply call:
alertPage.acceptAlert();
55. Page Methods for Frames
public void switchToPaymentFrame() {
WebElement frame =
driver.findElement(paymentFrame);
driver.switchTo()
.frame(frame);
}
A separate method can return to the main document:
public void switchToDefaultContent() {
driver.switchTo().defaultContent();
}
56. Page Methods for Windows and Tabs
public void switchToNewWindow() {
String currentWindow =
driver.getWindowHandle();
for (String window :
driver.getWindowHandles()) {
if (!window.equals(currentWindow)) {
driver.switchTo()
.window(window);
break;
}
}
}
57. Page Methods for File Upload
File upload can be encapsulated in a Page Method.
public void uploadFile(String filePath) {
driver.findElement(uploadInput)
.sendKeys(filePath);
}
Test:
profilePage.uploadFile(
"C:\\files\\profile.png"
);
58. Page Methods for Mouse Hover
public void hoverOverProducts() {
WebElement products =
driver.findElement(productsMenu);
Actions actions =
new Actions(driver);
actions.moveToElement(products)
.perform();
}
59. Page Methods for Drag and Drop
public void dragProductToCart() {
WebElement product =
driver.findElement(productElement);
WebElement cart =
driver.findElement(cartElement);
Actions actions =
new Actions(driver);
actions.dragAndDrop(
product,
cart
).perform();
}
60. Page Methods for Scrolling
public void scrollToBottom() {
((JavascriptExecutor) driver)
.executeScript(
"window.scrollTo(0, document.body.scrollHeight)"
);
}
61. Page Methods for Getting Product Information
public String getProductName() {
return driver.findElement(productName)
.getText();
}
public String getProductPrice() {
return driver.findElement(productPrice)
.getText();
}
Test:
Assert.assertEquals(
productPage.getProductName(),
"Laptop"
);
Assert.assertEquals(
productPage.getProductPrice(),
"$999"
);
62. Page Methods for Cart Operations
public void removeProduct(String product) {
By removeButton = By.xpath(
"//div[@class='cart-item']" +
"[.//span[normalize-space()='" +
product +
"']]//button"
);
driver.findElement(removeButton)
.click();
}
public void proceedToCheckout() {
driver.findElement(checkoutButton)
.click();
}
63. Page Methods for Login Validation
public boolean isLoginErrorDisplayed() {
try {
return driver.findElement(errorMessage)
.isDisplayed();
} catch (NoSuchElementException e) {
return false;
}
}
The test can verify:
Assert.assertTrue(
loginPage.isLoginErrorDisplayed()
);
64. Complete Page Method Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameField =
By.id("username");
private By passwordField =
By.id("password");
private By loginButton =
By.id("loginButton");
private By errorMessage =
By.id("errorMessage");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String username) {
driver.findElement(usernameField)
.clear();
driver.findElement(usernameField)
.sendKeys(username);
}
public void enterPassword(String password) {
driver.findElement(passwordField)
.clear();
driver.findElement(passwordField)
.sendKeys(password);
}
public void clickLogin() {
driver.findElement(loginButton)
.click();
}
public HomePage login(
String username,
String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
return new HomePage(driver);
}
public String getErrorMessage() {
return driver.findElement(errorMessage)
.getText();
}
}
65. Complete Test Using Page Methods
import org.testng.Assert;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void validLoginTest() {
LoginPage loginPage =
new LoginPage(driver);
HomePage homePage =
loginPage.login(
"admin",
"admin123"
);
Assert.assertEquals(
homePage.getPageTitle(),
"Dashboard"
);
}
@Test
public void invalidLoginTest() {
LoginPage loginPage =
new LoginPage(driver);
loginPage.enterUsername("invalid");
loginPage.enterPassword("wrong");
loginPage.clickLogin();
Assert.assertEquals(
loginPage.getErrorMessage(),
"Invalid credentials"
);
}
}
66. Page Methods vs Direct Selenium Commands
| Direct Selenium in Test | Page Methods |
| Locators exposed in tests | Locators encapsulated |
| More duplicate code | Less duplicate code |
| Harder to read | More readable |
| UI changes affect many tests | UI changes can often be handled in Page Objects |
| Less reusable | Highly reusable |
| Test and UI logic mixed | Test and UI logic separated |
67. Good Page Method Naming
Page Method names should describe the action or service clearly.
enterUsername()
enterPassword()
clickLogin()
searchProduct()
selectCategory()
addProductToCart()
removeProduct()
proceedToCheckout()
getProductPrice()
isErrorMessageDisplayed()
Avoid unclear names such as method1(), clickSomething(), or performAction().
68. Common Mistakes in Page Methods
- Putting all Selenium code directly in test classes.
- Exposing locators unnecessarily.
- Using unclear method names.
- Creating extremely large methods that perform unrelated actions.
- Duplicating the same Selenium interaction in multiple methods.
- Putting test assertions throughout Page Objects.
- Hard-coding test data unnecessarily inside Page Methods.
- Using Thread.sleep() everywhere instead of proper synchronization.
- Sharing unsafe WebDriver instances between parallel tests.
- Making Page Methods dependent on unrelated pages.
- Returning WebElements when a higher-level service method would be clearer.
69. Best Practices for Page Methods
- Keep Page Methods focused on page behavior.
- Use meaningful method names.
- Keep locators private where practical.
- Keep test assertions in test classes.
- Return another Page Object when navigation occurs.
- Return
this when fluent chaining is appropriate.
- Use parameters for reusable actions.
- Keep synchronization close to the interaction that requires it.
- Reuse smaller methods inside larger workflow methods.
- Avoid duplicating Selenium code.
- Keep Page Objects independent of specific test scenarios.
- Use Data Providers for large sets of test data rather than duplicating Page Methods.
- Keep sensitive information out of source-controlled test code.
70. Page Methods and Single Responsibility
A Page Method should generally have one clear responsibility.
For example:
public void enterUsername(String username) {
// Only enters username
}
A complete workflow can then combine focused methods:
public HomePage login(
String username,
String password) {
enterUsername(username);
enterPassword(password);
return submitLogin();
}
This structure improves reuse because individual methods can be used independently when required.
71. Page Methods and Abstraction
Page Methods provide abstraction by hiding Selenium implementation details from test classes.
Test:
loginPage.login("admin", "admin123");
The test does not need to know whether the Page Object uses:
By.id()
By.name()
By.cssSelector()
By.xpath()
- Explicit waits
- JavaScript execution
- Actions API
Those implementation details remain inside the Page Object.
72. Page Methods and Encapsulation
Encapsulation means keeping page-specific implementation details inside the Page Object and exposing meaningful public methods to the test.
private By loginButton =
By.id("loginButton");
public void clickLogin() {
driver.findElement(loginButton).click();
}
The locator is private, while the page service is public.
73. Page Methods and Page Navigation Flow
LoginPage
|
| login()
v
HomePage
|
| searchProduct()
v
SearchResultsPage
|
| addProductToCart()
v
CartPage
|
| proceedToCheckout()
v
CheckoutPage
|
| placeOrder()
v
OrderConfirmationPage
This structure models the user's journey through the application and keeps navigation logic inside the relevant Page Objects.
74. Practical E-Commerce Page Methods
public class ProductPage {
private WebDriver driver;
public ProductPage(WebDriver driver) {
this.driver = driver;
}
public void selectProduct(String product) {
// Product selection logic
}
public void selectQuantity(int quantity) {
// Quantity selection logic
}
public CartPage addToCart() {
// Add product logic
return new CartPage(driver);
}
}
Test:
CartPage cartPage =
productPage
.selectProduct("Laptop")
.addToCart();
75. Practical Login Framework Structure
src
|-- test
|-- java
|-- pages
| |-- LoginPage.java
| |-- HomePage.java
| |-- ProductPage.java
| |-- CartPage.java
| |-- CheckoutPage.java
|
|-- tests
| |-- LoginTest.java
| |-- ProductTest.java
| |-- CheckoutTest.java
|
|-- utilities
|-- DriverFactory.java
|-- ConfigReader.java
|-- ExcelReader.java
The pages package contains Page Objects and their Page Methods, while the tests package contains test scenarios and assertions.
76. Real-World Page Method Architecture
Test Data
|
v
Test Class
|
v
Page Method
|
v
Page Object
|
+-- Locators
|
+-- Synchronization
|
+-- Selenium Actions
|
v
Web Application
|
v
Page Result
|
v
Assertion
|
v
Test Report
77. Page Methods with Page Object Components
Modern applications often contain reusable components such as headers, navigation bars, product cards, filters, menus, and tables. These components can have their own methods.
public class HeaderComponent {
public void openCart() {
// Open cart
}
public void logout() {
// Logout
}
}
public class ProductComponent {
public String getProductName() {
return "";
}
public void addToCart() {
// Add product
}
}
This component-based approach can reduce duplication in applications where the same UI sections appear on many pages.
78. Page Methods and Reusable Business Workflows
High-level Page Methods can represent complete business workflows.
public OrderConfirmationPage purchaseProduct(
String productName,
int quantity) {
selectProduct(productName);
selectQuantity(quantity);
addToCart();
return checkout();
}
Test:
OrderConfirmationPage confirmation =
productPage.purchaseProduct(
"Laptop",
1
);
79. Page Methods Should Not Become God Methods
A common mistake is creating one huge Page Method that performs an entire end-to-end business process, including unrelated pages, data setup, assertions, and cleanup.
Instead of:
performEverything();
prefer focused methods:
login();
searchProduct();
addProductToCart();
proceedToCheckout();
placeOrder();
These methods can still be combined into a higher-level workflow when that workflow is genuinely useful.
80. Page Methods and Assertions - Recommended Pattern
A Page Object should generally expose information that a test can verify instead of performing the verification itself.
Page Object:
public String getWelcomeMessage() {
return driver.findElement(welcomeMessage)
.getText();
}
Test:
Assert.assertEquals(
homePage.getWelcomeMessage(),
"Welcome Admin"
);
This keeps the expected test outcome in the test class.
81. Page Methods and Error Handling
Page Methods should fail clearly when an expected application interaction cannot be completed. Framework-specific exception handling can be added where it provides useful diagnostic information.
public void clickLogin() {
try {
driver.findElement(loginButton)
.click();
} catch (NoSuchElementException e) {
throw new RuntimeException(
"Login button was not found",
e
);
}
}
In larger frameworks, custom exceptions and centralized logging may be used instead of generic exception wrapping.
82. Page Methods and Logging
Logging can help identify which Page Method was executing when a failure occurred.
public void login(
String username,
String password) {
System.out.println(
"Executing login for user: " + username
);
enterUsername(username);
enterPassword(password);
clickLogin();
}
In production frameworks, a logging framework such as SLF4J with an appropriate backend is generally preferable to extensive System.out.println() usage.
83. Page Methods and Screenshots
Screenshot handling is often better centralized in a utility or reporting layer, but Page Methods can expose meaningful state information that helps the reporting layer identify where a failure occurred.
public String getPageName() {
return "Login Page";
}
The reporting framework can use such information together with the failed test and screenshot.
84. Page Methods and Parallel Execution
When Selenium tests execute in parallel, each test execution should generally use an isolated WebDriver session. Page Objects should use the driver associated with the current test instance rather than sharing an unsafe static driver across threads.
Test Thread 1
|
v
Driver 1
|
v
LoginPage 1
Test Thread 2
|
v
Driver 2
|
v
LoginPage 2
85. Page Methods with Thread-Safe Driver Management
A framework can use a Driver Factory or ThreadLocal-based design to provide an isolated driver to each parallel test thread.
public class DriverFactory {
private static ThreadLocal<WebDriver> driver =
new ThreadLocal<>();
public static void setDriver(
WebDriver webDriver) {
driver.set(webDriver);
}
public static WebDriver getDriver() {
return driver.get();
}
public static void quitDriver() {
if (driver.get() != null) {
driver.get().quit();
driver.remove();
}
}
}
86. Page Methods and Page Factory
Page Factory is one possible implementation style for page objects. It can use annotations such as @FindBy to represent page elements. Page Factory is related to POM but is not the same concept: POM is the design pattern, while Page Factory is a mechanism that can be used to initialize page elements.
public class LoginPage {
private WebDriver driver;
@FindBy(id = "username")
private WebElement username;
@FindBy(id = "password")
private WebElement password;
@FindBy(id = "loginButton")
private WebElement loginButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(
driver,
this
);
}
public void login(
String user,
String pass) {
username.sendKeys(user);
password.sendKeys(pass);
loginButton.click();
}
}
87. Page Methods Using By Locators vs WebElements
| By Locators | WebElement Fields |
| Locators are stored as By objects | Elements are represented as WebElement fields |
| Elements can be found when the method needs them | Often initialized through Page Factory or explicit lookup |
| Works naturally with explicit waits | Can be convenient for traditional POM styles |
| Common modern Selenium approach | Common in traditional Page Factory implementations |
88. Practical Complete POM Example
public class LoginPage {
private final WebDriver driver;
private final By username =
By.id("username");
private final By password =
By.id("password");
private final By loginButton =
By.id("loginButton");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public LoginPage enterUsername(
String value) {
driver.findElement(username)
.clear();
driver.findElement(username)
.sendKeys(value);
return this;
}
public LoginPage enterPassword(
String value) {
driver.findElement(password)
.clear();
driver.findElement(password)
.sendKeys(value);
return this;
}
public HomePage submitLogin() {
driver.findElement(loginButton)
.click();
return new HomePage(driver);
}
public HomePage login(
String username,
String password) {
return enterUsername(username)
.enterPassword(password)
.submitLogin();
}
}
89. Complete Test Using the POM
public class LoginTest {
@Test
public void validLoginTest() {
LoginPage loginPage =
new LoginPage(driver);
HomePage homePage =
loginPage.login(
"admin",
"admin123"
);
Assert.assertEquals(
homePage.getPageTitle(),
"Dashboard"
);
}
}
The test expresses the user workflow without exposing the underlying Selenium locators.
90. Advantages of Page Methods
- Reusability: The same method can be used by multiple tests.
- Maintainability: UI implementation details are centralized.
- Readability: Test cases become closer to business workflows.
- Abstraction: Tests do not need to know locator implementation details.
- Encapsulation: Page-specific data and behavior stay together.
- Scalability: The approach works well as the automation suite grows.
- Reduced Duplication: Common Selenium operations are implemented once.
- Better Collaboration: Team members can understand page services more easily.
- Easier UI Maintenance: Locator changes can often be handled inside Page Objects.
91. Limitations and Considerations
- Poorly designed Page Objects can become very large.
- Overly generic Page Methods can become difficult to understand.
- Complex workflows may require multiple Page Objects and components.
- Incorrect abstraction can hide important test behavior.
- Excessive method chaining can reduce readability.
- Page Methods should not contain unrelated test logic.
- Large frameworks require consistent naming and architectural conventions.
92. Page Methods vs Hard-Coded Selenium
| Hard-Coded Selenium | Page Methods |
| Locators repeated in tests | Locators centralized |
| UI logic mixed with validation | UI logic separated |
| Difficult to maintain | Easier to maintain |
| Low reusability | High reusability |
| Tests become verbose | Tests become concise |
| UI changes may affect many tests | Changes can often be isolated to Page Objects |
93. Page Methods vs Utility Methods
| Page Method | Utility Method |
| Specific to a page/component | Usually generic and reusable |
| Uses page-specific locators | Usually independent of a particular page |
| Example: login() | Example: takeScreenshot() |
| Example: addProductToCart() | Example: readExcel() |
| Represents page behavior | Provides framework support |
94. Recommended Page Method Design
Page Object
|
+-- Private Locators
|
+-- Constructor
|
+-- Small Interaction Methods
| |
| +-- enterUsername()
| +-- enterPassword()
| +-- clickLogin()
|
+-- High-Level Workflow Methods
| |
| +-- login()
| +-- register()
|
+-- Information Methods
|
+-- getErrorMessage()
+-- getPageTitle()
+-- isElementDisplayed()
95. Interview Questions on Page Methods
1. What is a Page Method?
A Page Method is a method inside a Page Object that represents an action, operation, or service provided by a web page or component.
2. Why are Page Methods used in Selenium?
They encapsulate Selenium interaction logic, reduce duplication, improve readability, and make automation code easier to maintain.
3. Where should Page Methods be created?
They are normally created inside Page Object classes representing application pages or reusable page components.
4. Should locators be written inside test classes?
In a POM design, page-specific locators are generally kept inside the corresponding Page Object rather than duplicated across tests.
5. Can a Page Method accept parameters?
Yes. Parameters make Page Methods reusable with different input values.
6. Can a Page Method return a value?
Yes. It can return strings, booleans, numbers, collections, Page Objects, or other appropriate values.
7. Can a Page Method return another Page Object?
Yes. This is useful when an action navigates to another page.
8. What is method chaining in POM?
Method chaining occurs when Page Methods return this or another Page Object so multiple operations can be called in a fluent sequence.
9. Should Page Methods contain assertions?
Generally, Page Objects should provide page services and information, while tests should contain assertions about expected behavior.
10. What is the difference between a Page Method and a Test Method?
A Page Method performs page interaction, while a Test Method represents and validates a test scenario.
11. Can Page Methods use explicit waits?
Yes. Synchronization for page-specific elements can be encapsulated within Page Methods where appropriate.
12. Can Data Providers call Page Methods?
Yes. TestNG Data Providers can supply data to test methods, and those test methods can call reusable Page Methods.
13. Why should Page Methods have meaningful names?
Meaningful names make tests easier to understand and allow the Page Object to communicate application behavior clearly.
14. What is a high-level Page Method?
A high-level Page Method represents a complete logical workflow, such as login(), registerUser(), or checkout().
15. What is a low-level Page Method?
A low-level Page Method usually performs one focused interaction, such as entering text or clicking a specific button.
16. Can Page Methods be used with Page Factory?
Yes. Page Factory can be used to initialize page elements while Page Methods define the operations performed on those elements.
17. How do Page Methods improve maintenance?
They centralize page-specific interaction logic, so changes to UI locators or interaction details can often be handled in one Page Object.
18. Can Page Methods be used for dynamic elements?
Yes. A Page Method can construct dynamic locators based on method parameters.
19. Can Page Methods be reused across multiple tests?
Yes. Reusability is one of the primary benefits of Page Object design.
20. What is the most important principle when designing Page Methods?
Page Methods should clearly represent the services or behaviors of the page while hiding unnecessary implementation details from the test.
96. Quick Reference Table
| Concept | Example | Purpose |
| Page Method | login() | Represents page behavior |
| Input Method | enterUsername() | Enters data |
| Click Method | clickLogin() | Performs click action |
| Getter Method | getErrorMessage() | Reads page information |
| Boolean Method | isLoginDisplayed() | Returns page state |
| Navigation Method | openCart() | Navigates to another page |
| Workflow Method | login() | Combines multiple actions |
| Fluent Method | enterUsername() | Returns this for chaining |
| Page Transition | submitLogin() | Returns another Page Object |
97. Learning Roadmap for Page Methods
- Understand Selenium WebDriver basics.
- Learn the Page Object Model.
- Create basic Page Classes.
- Define private page locators.
- Create simple Page Methods.
- Pass parameters to Page Methods.
- Return values from Page Methods.
- Return other Page Objects after navigation.
- Learn fluent Page Methods and method chaining.
- Use explicit waits inside appropriate Page Methods.
- Combine Page Methods with TestNG.
- Combine Page Methods with Data Providers.
- Build reusable Page Components.
- Create Base Page functionality.
- Integrate Page Objects with Driver Factory.
- Build a complete scalable Selenium automation framework.
98. Practical Exercises
- Create a LoginPage class with username and password methods.
- Create a clickLogin() Page Method.
- Create a login() workflow method.
- Create a method that returns the login error message.
- Create a HomePage with logout functionality.
- Create a SearchPage with a parameterized searchProduct() method.
- Create a ProductPage with addProductToCart().
- Create a CartPage with removeProduct() and proceedToCheckout().
- Create Page Methods for an e-commerce checkout workflow.
- Use TestNG DataProvider with login().
- Implement fluent Page Methods using method chaining.
- Implement Page Methods that return another Page Object after navigation.
- Add explicit waits to important Page Methods.
- Create reusable Header and Navigation components.
- Build a complete Selenium POM project using Page Methods.
99. Real-World Page Method Flow
Test Case
|
v
loginPage.login(username, password)
|
+-- enterUsername()
|
+-- enterPassword()
|
+-- clickLogin()
|
v
HomePage
|
+-- searchProduct()
|
v
SearchResultsPage
|
+-- selectProduct()
|
v
ProductPage
|
+-- addToCart()
|
v
CartPage
|
+-- proceedToCheckout()
|
v
CheckoutPage
|
+-- placeOrder()
|
v
OrderConfirmationPage
|
v
Assertions / Test Report
100. Summary
Page Methods are an essential part of a maintainable Selenium Page Object Model. They represent the actions and services provided by a web page while hiding the underlying Selenium implementation from test classes.
A good Page Method should have a clear responsibility, meaningful name, appropriate parameters, and a useful return type when required. Small interaction methods such as enterUsername() and clickLogin() can be combined into higher-level workflow methods such as login().
Page Methods can return strings, booleans, collections, this, or other Page Objects depending on the operation. Returning another Page Object is particularly useful for modeling page navigation, while returning this can support fluent method chaining.
Page Methods work especially well with TestNG, Data Providers, explicit waits, Page Components, Page Factory, Driver Factory, reporting, and CI/CD frameworks. They help keep Selenium locators and interaction logic centralized while allowing test classes to focus on business scenarios and assertions.
Final Takeaway: A well-designed Page Method should make a Selenium test read like a user workflow while keeping the technical details of locators, WebDriver commands, synchronization, and page structure inside the Page Object.
101. Course Resources