0
0
Selenium Javatesting~5 mins

Utility classes in Selenium Java

Choose your learning style9 modes available
Introduction

Utility classes help you reuse common code easily. They keep your tests clean and simple.

When you need to perform the same action in many tests, like clicking buttons or entering text.
When you want to handle browser setup and cleanup in one place.
When you want to read data from files or databases for your tests.
When you want to wait for elements or handle common exceptions smoothly.
When you want to keep your test code organized and avoid repeating code.
Syntax
Selenium Java
public class UtilityClassName {
    // Static methods for common tasks
    public static void methodName() {
        // code here
    }
}

Utility classes usually have static methods so you can call them without creating an object.

Keep utility methods focused on one task for easy reuse.

Examples
This utility method pauses the test for a given number of seconds.
Selenium Java
public class BrowserUtils {
    public static void waitFor(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
This method clicks on an element found by the locator.
Selenium Java
public class ElementUtils {
    public static void clickElement(WebDriver driver, By locator) {
        driver.findElement(locator).click();
    }
}
Sample Program

This test opens a browser, waits 2 seconds using the utility method, clicks the <h1> element, prints a message, and closes the browser.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class BrowserUtils {
    public static void waitFor(int seconds) {
        try {
            Thread.sleep(seconds * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

public class TestExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        BrowserUtils.waitFor(2); // wait 2 seconds

        driver.findElement(By.tagName("h1")).click();

        System.out.println("Test completed successfully");
        driver.quit();
    }
}
OutputSuccess
Important Notes

Always keep utility classes simple and focused on reusable tasks.

Use clear method names to make your test code easy to read.

Remember to handle exceptions properly in utility methods to avoid test failures.

Summary

Utility classes help reuse common code in tests.

They usually contain static methods for easy access.

Using utility classes keeps tests clean and organized.