Mastering Java Enums for Test Automation

Mastering Java Enums for Automation

Enums in Java provide a clean, type-safe way to represent fixed sets of constants. In real-world Selenium automation, enums can make your code more readable, maintainable, and scalable. Let’s explore how enums are applied in a professional Selenium TestNG + Maven framework.

1. What Are Enums in Java?

Enums define a set of named constants. Unlike regular constants, they provide compile-time type safety and can hold additional behavior.

Example:

public enum BrowserType {
CHROME,
FIREFOX,
EDGE
}

2. Enums for Browser and Environment

Enums can manage cross-browser execution and environment switching:

DriverType.java

package com.demo.enums;

public enum DriverType {
CHROME,
FIREFOX,
EDGE
}

EnvironmentType.java

package com.demo.enums;

public enum EnvironmentType {
DEV,
STAGING,
PROD
}

Comment: Here, enums DriverType and EnvironmentType are used to restrict the browser and environment values to a predefined list, ensuring no accidental typos or unsupported options.

3. Real-World Folder Structure

selenium-automation/
│── pom.xml
│── testng.xml

├── src
├── main
│ └── test
│ └── com
│ └── demo
│ ├── base
│ │ └── BaseClass.java
│ ├── enums
│ │ ├── DriverType.java
│ │ └── EnvironmentType.java
│ ├── pages
│ │ └── LoginPage.java
│ ├── utilities
│ │ └── ExtentManager.java
│ └── actiondriver
│ | └── ActionDriver.java
| |
│ └── tests
│ └── LoginTest.java

└── resources
└── config.properties

4. BaseClass — Using Enums for Setup

package com.demo.base;


import com.demo.actiondriver.ActionDriver;
import com.demo.enums.DriverType;
import com.demo.enums.EnvironmentType;
import com.demo.utilities.ExtentManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.asserts.SoftAssert;


import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;


public class BaseClass {


protected static Properties prop;
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
private static ThreadLocal<ActionDriver> actionDriver = new ThreadLocal<>();
protected ThreadLocal<SoftAssert> softAssert = ThreadLocal.withInitial(SoftAssert::new);


public static final Logger logger = LogManager.getLogger(BaseClass.class);


@BeforeSuite
public void loadConfig() throws IOException {
prop = new Properties();
FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "/src/test/resources/config.properties");
prop.load(fis);
logger.info("Config.properties file loaded");
}


@BeforeMethod
public synchronized void setup() {
String browser = prop.getProperty("browser").toUpperCase();
String environment = prop.getProperty("environment").toUpperCase();


// Convert string values from properties to enum constants
DriverType driverType = DriverType.valueOf(browser);
EnvironmentType environmentType = EnvironmentType.valueOf(environment);


launchBrowser(driverType);
configureBrowser(environmentType);


actionDriver.set(new ActionDriver(getDriver()));
logger.info("ActionDriver initialized for thread: " + Thread.currentThread().getId());
}


private synchronized void launchBrowser(DriverType driverType) {
switch (driverType) {
case CHROME:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-notifications");
driver.set(new ChromeDriver(chromeOptions));
break;
case FIREFOX:
FirefoxOptions firefoxOptions = new FirefoxOptions();
driver.set(new FirefoxDriver(firefoxOptions));
break;
case EDGE:
EdgeOptions edgeOptions = new EdgeOptions();
driver.set(new EdgeDriver(edgeOptions));
break;
}


private void configureBrowser(EnvironmentType environmentType) {
int implicitWait = Integer.parseInt(prop.getProperty("implicitWait"));
getDriver().manage().timeouts().implicitlyWait(Duration.ofSeconds(implicitWait));
getDriver().manage().window().maximize();


// Use enum to control environment-specific URLs
switch (environmentType) {
case DEV:
getDriver().get("https://dev.demo.com");
break;
case STAGING:
getDriver().get("https://staging.demo.com");
break;
case PROD:
getDriver().get("https://demo.com");
break;
}
}


@AfterMethod
public synchronized void tearDown() {
if (driver.get() != null) {
getDriver().quit();
}
driver.remove();
actionDriver.remove();
logger.info("WebDriver instance closed.");
}


public static WebDriver getDriver() {
return driver.get();
}


public static ActionDriver getActionDriver() {
return actionDriver.get();
}


public SoftAssert getSoftAssert() {
return softAssert.get();
}


public void staticWait(int seconds) {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(seconds));
}

}

Comment: Here, enums are directly mapped from config.properties. This prevents invalid browser or environment strings from being passed, improving code safety.

5. config.properties Example

browser=chrome
environment=staging
implicitWait=10

6. Page Object Example

package com.demo.pages;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;


public class LoginPage {


private WebDriver driver;
private By username = By.id("txtUsername");
private By password = By.id("txtPassword");
private By loginBtn = By.id("btnLogin");


public LoginPage(WebDriver driver) {
this.driver = driver;
}


public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}

}

7. Test Class Example

package com.demo.tests;


import com.demo.base.BaseClass;
import com.demo.pages.LoginPage;
import org.testng.annotations.Test;


public class LoginTest extends BaseClass {


@Test
public void verifyLogin() {
LoginPage loginPage = new LoginPage(getDriver());
loginPage.login("admin", "admin123");


// Simple assertion
getSoftAssert().assertTrue(getDriver().getTitle().contains("DEMO"));
}

}

Final Thoughts

  • DriverType enum ensures cross-browser support.
  • EnvironmentType enum allows seamless environment switching (DEV → STAGING → PROD).
  • BaseClass centralizes driver setup & teardown, making test classes cleaner.
  • Configurations are externalized in properties file, so no code changes are required when switching browsers or environments.

🙌 Follow & Share

If this guide on Mastering Java Enums in Test Automation helped you:

  • Follow me for more advanced Selenium, TestNG, and Java automation tips.
  • Share this article with your QA team and fellow automation engineers.
  • Connect with me on X/Twitter, LinkedIn, and other platforms where testers thrive!

Social Media: LinkedIn, Twitter, Instagram, YouTube, GitHub.


Mastering Java Enums for Test Automation was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.

This post first appeared on Read More