1. Why Use Reusable Methods in Selenium?
In Selenium automation:
Many actions (clicking buttons, entering text, waiting for elements) are repeated across tests.
Writing the same code repeatedly increases maintenance burden.
Reusable methods promote cleaner, more maintainable, and readable tests.
Benefits:
DRY principle (Don’t Repeat Yourself)
Easier updates if locators or actions change
Standardized handling of waits, exceptions, and logging
2. Structure of Reusable Methods
Common approach:
Utility Class: A separate class containing static or instance methods
Methods for common actions: Click, send keys, wait, select dropdowns, capture screenshots
Example package structure:
src/test/java/
├─ utils/
│ └─ SeleniumUtils.java
└─ tests/
└─ LoginTest.java
3. Example Reusable Methods in Java
package utils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class SeleniumUtils {
// Wait for an element to be visible
public static WebElement waitForElement(WebDriver driver, By locator, int timeoutSeconds) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeoutSeconds));
return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
// Click an element safely
public static void clickElement(WebDriver driver, By locator, int timeoutSeconds) {
WebElement element = waitForElement(driver, locator, timeoutSeconds);
element.click();
}
// Send text to an input field
public static void enterText(WebDriver driver, By locator, String text, int timeoutSeconds) {
WebElement element = waitForElement(driver, locator, timeoutSeconds);
element.clear();
element.sendKeys(text);
}
// Check if an element is present
public static boolean isElementPresent(WebDriver driver, By locator, int timeoutSeconds) {
try {
waitForElement(driver, locator, timeoutSeconds);
return true;
} catch (TimeoutException e) {
return false;
}
}
// Capture screenshot
public static void takeScreenshot(WebDriver driver, String filePath) {
TakesScreenshot ts = (TakesScreenshot) driver;
File srcFile = ts.getScreenshotAs(OutputType.FILE);
File destFile = new File(filePath);
try {
org.openqa.selenium.io.FileHandler.copy(srcFile, destFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Using Reusable Methods in Tests
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import utils.SeleniumUtils;
public class LoginTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
By usernameField = By.id("username");
By passwordField = By.id("password");
By loginButton = By.id("loginBtn");
// Using reusable methods
SeleniumUtils.enterText(driver, usernameField, "testuser", 10);
SeleniumUtils.enterText(driver, passwordField, "password123", 10);
SeleniumUtils.clickElement(driver, loginButton, 10);
// Verify login
By welcomeMessage = By.id("welcomeMsg");
if (SeleniumUtils.isElementPresent(driver, welcomeMessage, 10)) {
System.out.println("Login successful!");
} else {
System.out.println("Login failed!");
SeleniumUtils.takeScreenshot(driver, "screenshots/login_fail.png");
}
driver.quit();
}
}
5. Best Practices for Reusable Selenium Methods
Always include explicit waits to handle dynamic web elements
Handle exceptions gracefully and log meaningful messages
Use descriptive method names (e.g., enterText, clickElement)
Keep locators in one place (Page Object Model)
Parameterize methods to make them flexible for different elements or test data
Avoid hardcoding paths or timeouts—use configuration files or constants
6. Advanced Reusable Patterns
Page Object Model (POM): Encapsulate page elements and actions
Base Test Class: Setup and teardown logic shared across tests
Custom Wait Utilities: Centralize all dynamic waits in one class
Data-Driven Utilities: Read test data from Excel, CSV, or JSON
Summary
Reusable methods in Java Selenium tests:
Reduce code duplication
Make tests more maintainable and readable
Handle waits, clicks, input, and screenshots consistently
Can be combined with Page Object Model for scalable test automation
Learn Selenium with JAVA Training in Hyderabad
Read More
How to Use Java Streams in Selenium Automation
Reading Data from Properties Files in Java
Creating Utility Classes for Common Selenium Functions
Java OOP Concepts for Selenium Testers
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments