Bird
Raised Fist0
Selenium Javatesting~15 mins

Utility classes in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Automate login using utility class for WebDriver setup
Preconditions (3)
Step 1: Use the utility class to initialize the WebDriver
Step 2: Navigate to the login page URL
Step 3: Enter 'testuser@example.com' in the email input field with id 'email'
Step 4: Enter 'Test@1234' in the password input field with id 'password'
Step 5: Click the login button with id 'loginBtn'
Step 6: Wait until the dashboard page loads and URL contains '/dashboard'
✅ Expected Result: User is successfully logged in and dashboard page is displayed with URL containing '/dashboard'
Automation Requirements - Selenium WebDriver with Java and TestNG
Assertions Needed:
Verify the current URL contains '/dashboard' after login
Best Practices:
Use a utility class to initialize and manage WebDriver instance
Use explicit waits to wait for page load or element presence
Use meaningful locators (id) for elements
Use TestNG assertions for validation
Automated Solution
Selenium Java
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.

Common Mistakes - 3 Pitfalls
Initializing WebDriver directly in each test without a utility class
Using Thread.sleep() instead of explicit waits
Using brittle locators like absolute XPath
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials

Show Hint

Practice

(1/5)
1. What is the main purpose of a utility class in Selenium Java testing?
easy
A. To define test case steps in detail
B. To store test data in variables
C. To create WebDriver instances for each test
D. To provide reusable static methods for common tasks

Solution

  1. Step 1: Understand utility class role

    Utility classes contain static methods to reuse code easily across tests.
  2. Step 2: Compare options with utility class purpose

    Only To provide reusable static methods for common tasks describes reusable static methods, which is the utility class purpose.
  3. Final Answer:

    To provide reusable static methods for common tasks -> Option D
  4. Quick Check:

    Utility class = reusable static methods [OK]
Hint: Utility classes hold static helpers for reuse [OK]
Common Mistakes:
  • Confusing utility class with test data storage
  • Thinking utility class creates WebDriver instances
  • Mixing utility class with test step definitions
2. Which of the following is the correct way to declare a utility method in Java?
easy
A. public static void openBrowser() {}
B. public void openBrowser() {}
C. void openBrowser() {}
D. static openBrowser() {}

Solution

  1. Step 1: Recall utility method syntax

    Utility methods are static so they can be called without creating an object.
  2. Step 2: Check each option's syntax

    public static void openBrowser() {} correctly declares a public static method with return type void.
  3. Final Answer:

    public static void openBrowser() {} -> Option A
  4. Quick Check:

    Utility method = public static method [OK]
Hint: Utility methods must be static for easy access [OK]
Common Mistakes:
  • Omitting static keyword
  • Missing return type
  • Incorrect method declaration syntax
3. Given this utility method:
public static String getPageTitle(WebDriver driver) {
    return driver.getTitle();
}

What will be the output if the current page title is "Home Page"?
medium
A. Compilation error
B. null
C. "Home Page"
D. driver.getTitle()

Solution

  1. Step 1: Understand method behavior

    The method returns the page title by calling driver.getTitle().
  2. Step 2: Check given page title

    The page title is "Home Page", so the method returns this string.
  3. Final Answer:

    "Home Page" -> Option C
  4. Quick Check:

    Method returns page title string [OK]
Hint: Method returns driver.getTitle() string [OK]
Common Mistakes:
  • Confusing method return with method name
  • Expecting null instead of actual title
  • Assuming syntax error without checking code
4. Identify the error in this utility class method:
public static void clickElement(WebElement element) {
    element.click;
}
medium
A. Missing parentheses after click method
B. WebElement cannot be passed as parameter
C. Method should return boolean
D. Static keyword is not allowed here

Solution

  1. Step 1: Check method syntax

    The method calls element.click but misses parentheses, which is invalid syntax.
  2. Step 2: Validate other options

    Passing WebElement is valid, return type void is fine, static allowed in utility methods.
  3. Final Answer:

    Missing parentheses after click method -> Option A
  4. Quick Check:

    Method call needs () after method name [OK]
Hint: Method calls need parentheses () [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Thinking WebElement can't be parameter
  • Assuming static keyword causes error
5. You want to create a utility class method that waits for an element to be visible before clicking it. Which approach is best?
hard
A. Add wait logic inside each test instead of utility method
B. Create a static method that uses WebDriverWait and then clicks the element
C. Create a non-static method that clicks element immediately without wait
D. Use Thread.sleep() inside utility method before clicking

Solution

  1. Step 1: Understand utility method purpose

    Utility methods should provide reusable, clean code for common tasks like waiting and clicking.
  2. Step 2: Evaluate options for best practice

    Create a static method that uses WebDriverWait and then clicks the element uses static method with WebDriverWait, which is efficient and reusable. Others are less reliable or not reusable.
  3. Final Answer:

    Create a static method that uses WebDriverWait and then clicks the element -> Option B
  4. Quick Check:

    Use static method with explicit wait [OK]
Hint: Use static method with WebDriverWait for reliable clicks [OK]
Common Mistakes:
  • Using Thread.sleep() causing slow tests
  • Not using static method for utility
  • Putting wait logic inside tests, not utility
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard