Utility classes in Selenium Java - Build an Automation Script
package tests; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import utils.DriverUtil; import java.time.Duration; public class LoginTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { driver = DriverUtil.getDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } @Test public void testValidLogin() { driver.get("https://example.com/login"); driver.findElement(By.id("email")).sendKeys("testuser@example.com"); driver.findElement(By.id("password")).sendKeys("Test@1234"); driver.findElement(By.id("loginBtn")).click(); wait.until(ExpectedConditions.urlContains("/dashboard")); String currentUrl = driver.getCurrentUrl(); Assert.assertTrue(currentUrl.contains("/dashboard"), "URL should contain '/dashboard' after login"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } } // utils/DriverUtil.java package utils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class DriverUtil { private static WebDriver driver; private DriverUtil() { // private constructor to prevent instantiation } public static WebDriver getDriver() { if (driver == null) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); } return driver; } public static void quitDriver() { if (driver != null) { driver.quit(); driver = null; } } }
The test class LoginTest uses the utility class DriverUtil to get the WebDriver instance. This avoids repeating WebDriver setup code in every test.
In @BeforeClass, we initialize the driver and explicit wait. The test navigates to the login page, enters credentials, clicks login, and waits until the URL contains '/dashboard'.
We assert that the URL contains '/dashboard' to confirm successful login.
In @AfterClass, we quit the driver to close the browser.
The utility class DriverUtil manages a single WebDriver instance with lazy initialization and maximizes the window. It also provides a method to quit the driver and clean up.
This structure keeps test code clean, reusable, and easy to maintain.
Now add data-driven testing with 3 different sets of login credentials