Complete Selenium + TestNG + Maven Automation Framework Guide (Advanced)
Technology: Java, Selenium 4, TestNG, Maven
This guide explains how to build a professional, reusable, scalable Selenium automation framework using Java, Selenium WebDriver, TestNG and Maven.
The framework includes Page Object Model, parallel execution, ThreadLocal WebDriver, configuration management, listeners, screenshots, Extent Reports, Log4j2 and CI/CD integration.
1. Technology Stack
| Technology | Purpose |
|---|---|
| Java 17+ | Programming language |
| Selenium 4 | Browser automation |
| TestNG | Test execution and assertions |
| Maven | Build and dependency management |
| WebDriverManager | Browser driver management |
| Extent Reports | HTML execution reports |
| Log4j2 | Logging |
| GitHub Actions | CI/CD |
Framework Architecture
TestNG Test Classes
|
v
Page Object Model
|
v
Base Test + WebDriver Factory
|
v
Selenium WebDriver
|
v
Web Application
Supporting Components:
- TestNG Listeners
- Extent Reports
- Configuration
- Log4j2
2. Prerequisites and Installation
Install the following tools:
- JDK 17 or newer
- IntelliJ IDEA or Eclipse
- Apache Maven
- Chrome, Firefox or Edge
- Git (optional)
Verify Java
java -version
Expected output:
openjdk version "17.x.x"
Verify Maven
mvn -version
Expected output:
Apache Maven 3.x.x
Java version: 17
OS name: Windows
3. Create Maven Project
Create a Maven project in IntelliJ IDEA.
- Project name: selenium-testng-maven
- Build system: Maven
- Language: Java
- JDK: 17+
- Packaging: JAR
Alternatively, create a Maven project using the command line:
mvn archetype:generate -DgroupId=com.automation -DartifactId=selenium-testng-maven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Navigate to the project:
cd selenium-testng-maven
4. Maven Project Directory Structure
selenium-testng-maven/
|
|-- pom.xml
|
|-- src/
| |-- main/
| | |-- java/
| | |-- com/automation/
| | |-- driver/
| | | |-- DriverFactory.java
| | |-- pages/
| | | |-- BasePage.java
| | | |-- LoginPage.java
| | | |-- DashboardPage.java
| | |-- utils/
| | |-- ConfigReader.java
| |
| |-- test/
| |-- java/
| | |-- com/automation/
| | |-- base/
| | | |-- BaseTest.java
| | |-- tests/
| | | |-- LoginTest.java
| | |-- listeners/
| | | |-- TestListener.java
| | |-- reporting/
| | |-- ExtentManager.java
| |
| |-- resources/
| |-- config.properties
| |-- log4j2.xml
| |-- testng.xml
|
|-- test-output/
|-- reports/
|-- screenshots/
5. Configure pom.xml
The pom.xml file manages dependencies, plugins, Java compilation and test execution.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.automation</groupId>
<artifactId>selenium-testng-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<selenium.version>4.38.0</selenium.version>
<testng.version>7.11.0</testng.version>
<webdrivermanager.version>6.3.3</webdrivermanager.version>
<extent.version>5.1.2</extent.version>
<log4j.version>2.25.2</log4j.version>
<browser>chrome</browser>
<environment>qa</environment>
<headless>false</headless>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>${extent.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.20.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<release>17</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<browser>${browser}</browser>
<environment>${environment}</environment>
<headless>${headless}</headless>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
Download dependencies:
mvn clean install -DskipTests
Expected output:
[INFO] BUILD SUCCESS
6. Selenium WebDriver Configuration
Create src/test/resources/config.properties.
baseUrl=https://www.saucedemo.com/
environment=qa
browser=chrome
headless=false
incognito=true
implicitWait=0
explicitWait=15
pageLoadTimeout=30
screenshotOnFailure=true
SauceDemo is used as a demonstration application.
7. ConfigReader.java
This utility reads properties from the configuration file and allows Maven system properties to override them.
package com.automation.utils;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
public final class ConfigReader {
private static final Properties PROPERTIES = new Properties();
static {
try (InputStream input =
ConfigReader.class.getClassLoader()
.getResourceAsStream("config.properties")) {
if (input == null) {
throw new IllegalStateException(
"config.properties not found");
}
PROPERTIES.load(input);
} catch (IOException e) {
throw new RuntimeException(
"Unable to load configuration", e);
}
}
private ConfigReader() {
}
public static String get(String key) {
String value = System.getProperty(
key, PROPERTIES.getProperty(key));
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(
"Missing configuration: " + key);
}
return value.trim();
}
public static String get(String key, String defaultValue) {
return System.getProperty(
key, PROPERTIES.getProperty(key, defaultValue)).trim();
}
public static boolean getBoolean(String key) {
return Boolean.parseBoolean(get(key));
}
public static int getInt(String key) {
return Integer.parseInt(get(key));
}
}
8. DriverFactory.java - Browser Management
DriverFactory creates and manages browser instances. ThreadLocal ensures each parallel thread receives its own WebDriver instance.
package com.automation.driver;
import com.automation.utils.ConfigReader;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import java.time.Duration;
public final class DriverFactory {
private static final ThreadLocal<WebDriver> DRIVER =
new ThreadLocal<>();
private DriverFactory() {
}
public static void initDriver(String browser) {
WebDriver driver;
switch (browser.toLowerCase()) {
case "chrome" -> {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
if (ConfigReader.getBoolean("headless")) {
options.addArguments("--headless=new");
}
if (ConfigReader.getBoolean("incognito")) {
options.addArguments("--incognito");
}
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
case "firefox" -> {
WebDriverManager.firefoxdriver().setup();
FirefoxOptions options = new FirefoxOptions();
if (ConfigReader.getBoolean("headless")) {
options.addArguments("-headless");
}
driver = new FirefoxDriver(options);
}
case "edge" -> {
WebDriverManager.edgedriver().setup();
EdgeOptions options = new EdgeOptions();
if (ConfigReader.getBoolean("headless")) {
options.addArguments("--headless=new");
}
driver = new EdgeDriver(options);
}
default -> throw new IllegalArgumentException(
"Unsupported browser: " + browser);
}
driver.manage().timeouts()
.implicitlyWait(Duration.ZERO);
driver.manage().timeouts()
.pageLoadTimeout(Duration.ofSeconds(
ConfigReader.getInt("pageLoadTimeout")));
DRIVER.set(driver);
}
public static WebDriver getDriver() {
WebDriver driver = DRIVER.get();
if (driver == null) {
throw new IllegalStateException(
"WebDriver is not initialized for this thread");
}
return driver;
}
public static void quitDriver() {
WebDriver driver = DRIVER.get();
try {
if (driver != null) {
driver.quit();
}
} finally {
DRIVER.remove();
}
}
}
Why ThreadLocal?
| Thread | Browser instance |
|---|---|
| Thread 1 | Chrome 1 |
| Thread 2 | Chrome 2 |
| Thread 3 | Chrome 3 |
| Thread 4 | Chrome 4 |
9. BasePage.java - Reusable Selenium Operations
package com.automation.pages;
import com.automation.driver.DriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.List;
public abstract class BasePage {
protected final WebDriver driver;
protected final WebDriverWait wait;
protected BasePage() {
this.driver = DriverFactory.getDriver();
this.wait = new WebDriverWait(
driver,
Duration.ofSeconds(15));
}
protected WebElement find(By locator) {
return wait.until(
ExpectedConditions.visibilityOfElementLocated(locator));
}
protected void click(By locator) {
wait.until(
ExpectedConditions.elementToBeClickable(locator))
.click();
}
protected void type(By locator, String value) {
WebElement element = find(locator);
element.clear();
element.sendKeys(value);
}
protected String getText(By locator) {
return find(locator).getText();
}
protected boolean isDisplayed(By locator) {
List<WebElement> elements = driver.findElements(locator);
return !elements.isEmpty() && elements.get(0).isDisplayed();
}
protected void waitForUrl(String url) {
wait.until(ExpectedConditions.urlContains(url));
}
}
10. LoginPage.java - Page Object Model
package com.automation.pages;
import org.openqa.selenium.By;
public class LoginPage extends BasePage {
private final By username = By.id("user-name");
private final By password = By.id("password");
private final By loginButton = By.id("login-button");
private final By errorMessage =
By.cssSelector("[data-test='error']");
public LoginPage enterUsername(String user) {
type(username, user);
return this;
}
public LoginPage enterPassword(String pass) {
type(password, pass);
return this;
}
public DashboardPage clickLogin() {
click(loginButton);
return new DashboardPage();
}
public LoginPage loginWithInvalidCredentials(
String user, String pass) {
enterUsername(user);
enterPassword(pass);
click(loginButton);
return this;
}
public String getErrorMessage() {
return getText(errorMessage);
}
}
Method Chaining Example
loginPage
.enterUsername("standard_user")
.enterPassword("secret_sauce")
.clickLogin();
11. DashboardPage.java
package com.automation.pages;
import org.openqa.selenium.By;
public class DashboardPage extends BasePage {
private final By pageTitle = By.cssSelector(".title");
private final By inventoryItems =
By.className("inventory_item");
private final By menuButton =
By.id("react-burger-menu-btn");
private final By logoutLink =
By.id("logout_sidebar_link");
public String getPageTitle() {
return getText(pageTitle);
}
public int getProductCount() {
return driver.findElements(inventoryItems).size();
}
public void logout() {
click(menuButton);
click(logoutLink);
}
}
12. BaseTest.java - Test Lifecycle Management
package com.automation.base;
import com.automation.driver.DriverFactory;
import com.automation.utils.ConfigReader;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTest {
protected WebDriver driver;
@BeforeMethod(alwaysRun = true)
public void setUp() {
String browser = ConfigReader.get("browser");
DriverFactory.initDriver(browser);
driver = DriverFactory.getDriver();
driver.get(ConfigReader.get("baseUrl"));
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
DriverFactory.quitDriver();
}
}
Execution Flow
@BeforeMethod
|
v
Initialize Browser
|
v
Navigate to Application
|
v
Execute @Test
|
v
@AfterMethod
|
v
Close Browser
13. LoginTest.java - Complete Test Examples
package com.automation.tests;
import com.automation.base.BaseTest;
import com.automation.pages.DashboardPage;
import com.automation.pages.LoginPage;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTest extends BaseTest {
@Test(
priority = 1,
groups = {"smoke", "regression"},
description = "Verify successful login"
)
public void verifySuccessfulLogin() {
LoginPage loginPage = new LoginPage();
DashboardPage dashboard = loginPage
.enterUsername("standard_user")
.enterPassword("secret_sauce")
.clickLogin();
Assert.assertEquals(
dashboard.getPageTitle(),
"Products",
"Dashboard title mismatch");
Assert.assertEquals(
dashboard.getProductCount(),
6,
"Product count mismatch");
}
@Test(
priority = 2,
groups = {"regression"},
description = "Verify invalid login"
)
public void verifyInvalidLogin() {
LoginPage loginPage = new LoginPage();
loginPage.loginWithInvalidCredentials(
"invalid_user",
"wrong_password");
Assert.assertTrue(
loginPage.getErrorMessage()
.contains("Username and password do not match"),
"Invalid login error message mismatch");
}
@Test(
dataProvider = "loginData",
groups = {"regression"}
)
public void verifyLoginWithData(
String username,
String password,
boolean expectedSuccess) {
LoginPage loginPage = new LoginPage();
if (expectedSuccess) {
DashboardPage dashboard = loginPage
.enterUsername(username)
.enterPassword(password)
.clickLogin();
Assert.assertEquals(
dashboard.getPageTitle(),
"Products");
} else {
loginPage.loginWithInvalidCredentials(
username, password);
Assert.assertTrue(
loginPage.getErrorMessage().contains("do not match"));
}
}
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"standard_user", "secret_sauce", true},
{"invalid_user", "wrong_password", false}
};
}
}
Expected Test Results
| Test Case | Result |
|---|---|
| verifySuccessfulLogin | PASS |
| verifyInvalidLogin | PASS |
| verifyLoginWithData - standard_user | PASS |
| verifyLoginWithData - invalid_user | PASS |
Illustrative summary: Tests run: 4, Failures: 0, Skips: 0.
14. TestNG Annotations
| Annotation | Purpose |
|---|---|
| @BeforeSuite | Executes before the entire suite |
| @AfterSuite | Executes after the entire suite |
| @BeforeTest | Executes before a TestNG XML test |
| @AfterTest | Executes after a TestNG XML test |
| @BeforeClass | Executes before the first method in a class |
| @AfterClass | Executes after all methods in a class |
| @BeforeMethod | Executes before each test method |
| @AfterMethod | Executes after each test method |
| @Test | Marks a test method |
| @DataProvider | Supplies test data |
| @Parameters | Reads XML parameters |
| @Factory | Creates test class instances |
| @Listeners | Registers listeners |
Annotation Execution Example
@BeforeSuite
public void beforeSuite() {
System.out.println("Before Suite");
}
@BeforeTest
public void beforeTest() {
System.out.println("Before Test");
}
@BeforeClass
public void beforeClass() {
System.out.println("Before Class");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("Before Method");
}
@Test
public void testMethod() {
System.out.println("Test Method");
}
@AfterMethod
public void afterMethod() {
System.out.println("After Method");
}
@AfterClass
public void afterClass() {
System.out.println("After Class");
}
@AfterTest
public void afterTest() {
System.out.println("After Test");
}
@AfterSuite
public void afterSuite() {
System.out.println("After Suite");
}
Expected execution order:
Before Suite
Before Test
Before Class
Before Method
Test Method
After Method
After Class
After Test
After Suite
15. TestNG Assertions
Hard Assertions
Execution stops immediately when a hard assertion fails.
Assert.assertEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertFalse(condition);
Assert.assertNotNull(object);
Assert.fail("Test failed");
Soft Assertions
Execution continues after assertion failures, and assertAll() reports accumulated failures.
import org.testng.asserts.SoftAssert;
@Test
public void verifyProductDetails() {
SoftAssert soft = new SoftAssert();
soft.assertEquals("Products", "Products");
soft.assertTrue(true);
soft.assertEquals("Sauce Labs Backpack", "Backpack");
soft.assertAll();
}
Expected output:
FAILED: verifyProductDetails
The following asserts failed:
expected [Backpack]
but found [Sauce Labs Backpack]
Always call assertAll() at the end of a soft assertion test.
16. TestNG Groups
@Test(groups = {"smoke"})
public void loginTest() {
System.out.println("Login test");
}
@Test(groups = {"regression"})
public void paymentTest() {
System.out.println("Payment test");
}
@Test(groups = {"smoke", "regression"})
public void searchTest() {
System.out.println("Search test");
}
Run smoke tests:
mvn test -Dgroups=smoke
Run regression tests:
mvn test -Dgroups=regression
17. Test Dependencies and Priority
Priority Example
@Test(priority = 1)
public void login() {
System.out.println("Login");
}
@Test(priority = 2)
public void search() {
System.out.println("Search");
}
@Test(priority = 3)
public void logout() {
System.out.println("Logout");
}
Output:
Login
Search
Logout
dependsOnMethods Example
@Test
public void login() {
System.out.println("Login");
}
@Test(dependsOnMethods = "login")
public void search() {
System.out.println("Search");
}
@Test(dependsOnMethods = "search")
public void logout() {
System.out.println("Logout");
}
If the login test fails, dependent tests are skipped by default. Prefer independent tests and use API setup or fixtures wherever possible.
18. TestNG DataProvider - Advanced Examples
Example 1: Multiple Users
@DataProvider(name = "users")
public Object[][] getUsers() {
return new Object[][] {
{"standard_user", "secret_sauce"},
{"problem_user", "secret_sauce"},
{"performance_glitch_user", "secret_sauce"}
};
}
@Test(dataProvider = "users")
public void loginTest(String username, String password) {
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
Example 2: Parallel DataProvider
@DataProvider(
name = "parallelUsers",
parallel = true
)
public Object[][] parallelUsers() {
return new Object[][] {
{"user1", "password1"},
{"user2", "password2"},
{"user3", "password3"},
{"user4", "password4"}
};
}
@Test(dataProvider = "parallelUsers")
public void parallelLoginTest(
String username, String password) {
System.out.println(
Thread.currentThread().getId()
+ " : " + username);
}
Parallel DataProvider execution requires independent test state. ThreadLocal WebDriver supports this model.
19. TestNG XML Configuration
Create src/test/resources/testng.xml.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Selenium Automation Suite"
parallel="classes"
thread-count="3"
verbose="2">
<listeners>
<listener class-name="com.automation.listeners.TestListener"/>
</listeners>
<test name="Chrome Regression Tests">
<parameter name="browser" value="chrome"/>
<groups>
<run>
<include name="smoke"/>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="com.automation.tests.LoginTest"/>
</classes>
</test>
</suite>
The browser XML parameter does not automatically override ConfigReader. Use either XML parameters or Maven system properties as your browser configuration source.
Parallel Options
| Configuration | Meaning |
|---|---|
| parallel="methods" | Runs methods in parallel |
| parallel="classes" | Runs classes in parallel |
| parallel="tests" | Runs XML test blocks in parallel |
| parallel="instances" | Runs class instances in parallel |
| thread-count="3" | Maximum parallel threads |
20. TestNG Listener Implementation
Listeners provide hooks for test execution events.
- onTestStart()
- onTestSuccess()
- onTestFailure()
- onTestSkipped()
- onStart()
- onFinish()
ScreenshotUtils.java
package com.automation.utils;
import com.automation.driver.DriverFactory;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public final class ScreenshotUtils {
private ScreenshotUtils() {
}
public static String capture(String testName) {
try {
Path directory = Path.of("screenshots");
Files.createDirectories(directory);
String timestamp = LocalDateTime.now()
.format(DateTimeFormatter
.ofPattern("yyyyMMdd_HHmmss_SSS"));
Path destination = directory.resolve(
testName + "_" + timestamp + ".png");
var source = ((TakesScreenshot)
DriverFactory.getDriver())
.getScreenshotAs(OutputType.FILE);
Files.copy(source.toPath(), destination);
return destination.toAbsolutePath().toString();
} catch (IOException e) {
throw new RuntimeException(
"Screenshot capture failed", e);
}
}
}
ExtentManager.java
package com.automation.reporting;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import java.nio.file.Files;
import java.nio.file.Path;
public final class ExtentManager {
private static ExtentReports extent;
private ExtentManager() {
}
public static synchronized ExtentReports getInstance() {
if (extent == null) {
try {
Files.createDirectories(Path.of("reports"));
} catch (Exception e) {
throw new RuntimeException(e);
}
ExtentSparkReporter spark =
new ExtentSparkReporter(
"reports/ExtentReport.html");
spark.config().setDocumentTitle(
"Automation Test Report");
spark.config().setReportName(
"Selenium Test Execution");
extent = new ExtentReports();
extent.attachReporter(spark);
extent.setSystemInfo("Framework", "Selenium + TestNG");
extent.setSystemInfo("Language", "Java");
}
return extent;
}
}
TestListener.java
package com.automation.listeners;
import com.automation.reporting.ExtentManager;
import com.automation.utils.ScreenshotUtils;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
private static final ExtentReports EXTENT =
ExtentManager.getInstance();
private static final ThreadLocal<ExtentTest> TEST =
new ThreadLocal<>();
@Override
public void onTestStart(ITestResult result) {
ExtentTest test = EXTENT.createTest(
result.getMethod().getMethodName());
TEST.set(test);
TEST.get().info("Test execution started");
}
@Override
public void onTestSuccess(ITestResult result) {
TEST.get().pass("Test passed successfully");
TEST.remove();
}
@Override
public void onTestFailure(ITestResult result) {
TEST.get().fail(result.getThrowable());
try {
String screenshot =
ScreenshotUtils.capture(
result.getMethod().getMethodName());
TEST.get().addScreenCaptureFromPath(screenshot);
} catch (Exception e) {
TEST.get().warning(
"Unable to attach screenshot: " + e.getMessage());
} finally {
TEST.remove();
}
}
@Override
public void onTestSkipped(ITestResult result) {
TEST.get().skip("Test skipped");
if (result.getThrowable() != null) {
TEST.get().skip(result.getThrowable());
}
TEST.remove();
}
@Override
public void onFinish(
org.testng.ITestContext context) {
EXTENT.flush();
}
}
Important: For reliable failure screenshots, capture the screenshot in an @AfterMethod that receives ITestResult, before quitting the browser. This avoids relying on listener ordering relative to browser cleanup.
21. Log4j2 Integration
Create src/main/resources/log4j2.xml.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss} %-5level %logger - %msg%n"/>
</Console>
<File name="File"
fileName="logs/automation.log"
append="true">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %logger - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
Logger Example
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ExampleLogger {
private static final Logger log =
LogManager.getLogger(ExampleLogger.class);
public void execute() {
log.info("Test execution started");
log.warn("This is a warning");
log.error("This is an error");
}
}
Expected console output:
12:00:00 INFO ExampleLogger - Test execution started
12:00:01 WARN ExampleLogger - This is a warning
12:00:02 ERROR ExampleLogger - This is an error
22. Selenium Waits and Synchronization
| Wait | Description |
|---|---|
| Implicit Wait | Global element lookup timeout |
| Explicit Wait | Waits for a particular condition |
| Fluent Wait | Explicit wait with custom polling and ignored exceptions |
| Thread.sleep() | Fixed delay; generally avoid |
Explicit Wait
WebDriverWait wait = new WebDriverWait(
driver, Duration.ofSeconds(15));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("login-button")));
Fluent Wait
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement element = fluentWait.until(
d -> d.findElement(By.id("login-button")));
Common ExpectedConditions
ExpectedConditions.visibilityOfElementLocated(locator);
ExpectedConditions.elementToBeClickable(locator);
ExpectedConditions.presenceOfElementLocated(locator);
ExpectedConditions.invisibilityOfElementLocated(locator);
ExpectedConditions.titleContains("Dashboard");
ExpectedConditions.urlContains("inventory");
ExpectedConditions.alertIsPresent();
ExpectedConditions.frameToBeAvailableAndSwitchToIt(locator);
Use explicit waits consistently. Avoid mixing implicit and explicit waits because their combined timeout behavior can be unpredictable.
23. Selenium Advanced Browser Interactions
Dropdown
Select dropdown = new Select(
driver.findElement(By.id("country")));
dropdown.selectByVisibleText("India");
dropdown.selectByValue("IN");
dropdown.selectByIndex(1);
JavaScriptExecutor
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].scrollIntoView({block:'center'});",
element);
JavaScript Click
js.executeScript("arguments[0].click();", element);
Actions Class
Actions actions = new Actions(driver);
actions.moveToElement(element)
.click()
.perform();
Drag and Drop
actions.dragAndDrop(source, target).perform();
Keyboard Actions
actions.sendKeys(Keys.CONTROL, "a")
.sendKeys("Automation Testing")
.perform();
Alert Handling
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
Window Handling
String parentWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
Frames
driver.switchTo().frame("frameName");
driver.findElement(By.id("submit")).click();
driver.switchTo().defaultContent();
24. TestNG Parallel Execution
Parallel execution reduces test execution time. For four independent tests that each take ten seconds, sequential execution takes approximately forty seconds, while four concurrent workers may finish in approximately ten seconds plus browser startup and system overhead.
Parallel TestNG XML
<suite name="ParallelSuite"
parallel="classes"
thread-count="4">
<test name="RegressionTests">
<classes>
<class name="com.automation.tests.LoginTest"/>
<class name="com.automation.tests.SearchTest"/>
<class name="com.automation.tests.CartTest"/>
<class name="com.automation.tests.CheckoutTest"/>
</classes>
</test>
</suite>
Run:
mvn clean test
Parallel Execution Best Practices
- Use ThreadLocal WebDriver.
- Avoid static mutable test data.
- Avoid sharing WebElement objects.
- Use unique test accounts or independent test data.
- Make report and screenshot filenames unique.
- Avoid tests depending on execution order.
- Ensure the application can handle concurrent traffic.
25. Maven Build Lifecycle
| Phase | Purpose |
|---|---|
| validate | Validates project structure |
| compile | Compiles main source code |
| test-compile | Compiles test source code |
| test | Executes tests |
| package | Packages the application |
| verify | Runs verification checks |
| install | Installs artifact locally |
| deploy | Publishes artifact to a repository |
Maven Commands
mvn clean
mvn compile
mvn test-compile
mvn test
mvn package
mvn verify
mvn install
Maven executes earlier lifecycle phases when you invoke a later phase. For example, mvn package also performs compilation and tests.
26. Maven Surefire and Failsafe Plugins
Surefire: Primarily used for unit and regular test execution during the Maven test phase.
Failsafe: Primarily used for integration tests during the integration-test and verify phases.
Failsafe Configuration
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.5.4</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
</plugin>
Test Naming Convention
| File | Plugin |
|---|---|
| LoginTest.java | Surefire |
| CheckoutIT.java | Failsafe |
| PaymentServiceIT.java | Failsafe |
27. Execute Tests Using Maven Commands
| Command | Purpose |
|---|---|
| mvn clean | Remove previous build files |
| mvn test | Execute tests |
| mvn clean test | Clean and execute tests |
| mvn package | Build JAR package |
| mvn install | Install project locally |
| mvn test -DskipTests | Skip test execution |
| mvn test -Dtest=LoginTest | Execute a specific test class |
| mvn test -Dgroups=smoke | Execute smoke tests |
| mvn test -Dbrowser=firefox | Execute on Firefox |
| mvn test -Dbrowser=edge | Execute on Edge |
| mvn test -Dheadless=true | Request headless mode |
Headless Execution
mvn clean test -Dbrowser=chrome -Dheadless=true
Expected Maven Output
[INFO] Scanning for projects...
[INFO] Building selenium-testng-maven
[INFO] Running com.automation.tests.LoginTest
PASSED: verifySuccessfulLogin
PASSED: verifyInvalidLogin
PASSED: verifyLoginWithData
PASSED: verifyLoginWithData
===============================================
Selenium Automation Suite
Tests run: 4, Failures: 0, Skips: 0
===============================================
[INFO] BUILD SUCCESS
28. GitHub Actions CI/CD Integration
Create .github/workflows/selenium-tests.yml.
name: Selenium TestNG Maven Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
workflow_dispatch:
jobs:
selenium-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
cache: maven
- name: Execute Selenium Tests
run: |
mvn clean test \
-Dbrowser=chrome \
-Dheadless=true
- name: Upload Test Reports
if: always()
uses: actions/upload-artifact@v4
with:
name: selenium-test-reports
path: |
target/surefire-reports/
reports/
screenshots/
if-no-files-found: ignore
retention-days: 14
Pipeline Execution Flow
Git Push / Pull Request
|
v
Checkout Source Code
|
v
Install Java + Maven
|
v
Execute Selenium Tests
|
v
Generate TestNG + Extent Reports
|
v
Upload Reports and Screenshots
Jenkins Integration
Create Jenkinsfile in the project root.
pipeline {
agent any
tools {
jdk 'JDK17'
maven 'Maven'
}
parameters {
choice(
name: 'BROWSER',
choices: ['chrome', 'firefox', 'edge'],
description: 'Select browser'
)
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Execute Tests') {
steps {
sh """
mvn clean test \
-Dbrowser=${params.BROWSER} \
-Dheadless=true
"""
}
}
stage('Publish Reports') {
steps {
archiveArtifacts(
artifacts: 'reports/**,screenshots/**',
allowEmptyArchive: true
)
junit(
testResults: 'target/surefire-reports/*.xml',
allowEmptyResults: true
)
}
}
}
post {
always {
echo 'Automation execution completed'
}
}
}
On Windows Jenkins agents, replace sh with bat.
29. Handling Exceptions in Selenium
| Exception | Reason |
|---|---|
| NoSuchElementException | Element not found |
| TimeoutException | Wait condition timed out |
| StaleElementReferenceException | Element reference is no longer valid |
| ElementNotInteractableException | Element cannot be interacted with |
| ElementClickInterceptedException | Another element intercepts the click |
| NoSuchWindowException | Browser window does not exist |
| NoSuchFrameException | Frame not found |
| InvalidSelectorException | Invalid XPath or CSS selector |
| SessionNotCreatedException | Browser session could not be created |
| UnhandledAlertException | Unexpected alert is present |
StaleElementReferenceException Example
WebElement element = driver.findElement(
By.id("username"));
driver.navigate().refresh();
element.sendKeys("sumit");
The stored element may become stale after refreshing the page.
Solution:
By username = By.id("username");
wait.until(
ExpectedConditions.visibilityOfElementLocated(username)
).sendKeys("sumit");
ElementClickInterceptedException
WebDriverWait wait = new WebDriverWait(
driver, Duration.ofSeconds(10));
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("submit-button")
)).click();
Investigate overlays, animations and sticky elements rather than automatically replacing every click with JavaScript.
30. Cross-Browser Testing
Our DriverFactory supports Chrome, Firefox and Edge.
Chrome
mvn clean test -Dbrowser=chrome
Firefox
mvn clean test -Dbrowser=firefox
Edge
mvn clean test -Dbrowser=edge
A useful CI strategy is to run a small smoke suite across all supported browsers and execute the larger regression suite on your primary browser.
31. Advanced TestNG Features
A. @Parameters
@Parameters("browser")
@BeforeMethod
public void setUp(@Optional("chrome") String browser) {
DriverFactory.initDriver(browser);
driver = DriverFactory.getDriver();
driver.get(ConfigReader.get("baseUrl"));
}
XML:
<parameter name="browser" value="firefox"/>
Use either this XML-based setup or the system-property-based setup. Do not define two competing browser initialization methods.
B. @Factory
public class BrowserTest {
private final String browser;
public BrowserTest(String browser) {
this.browser = browser;
}
@Test
public void browserTest() {
System.out.println(
"Running on: " + browser);
}
@Factory
public static Object[] createTests() {
return new Object[] {
new BrowserTest("chrome"),
new BrowserTest("firefox"),
new BrowserTest("edge")
};
}
}
Expected output:
Running on: chrome
Running on: firefox
Running on: edge
This demonstrates TestNG factory instances; it does not itself launch browsers.
C. Retry Failed Tests
Create RetryAnalyzer.java.
package com.automation.listeners;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private static final int MAX_RETRY = 2;
@Override
public boolean retry(ITestResult result) {
if (retryCount < MAX_RETRY) {
retryCount++;
System.out.println(
"Retrying test: "
+ result.getName()
+ " Attempt: " + retryCount);
return true;
}
return false;
}
}
Use it:
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testLogin() {
Assert.assertTrue(false);
}
Expected output:
Retrying test: testLogin Attempt: 1
Retrying test: testLogin Attempt: 2
FAILED: testLogin
Retries should be limited to known transient failures. Do not use retries to hide genuine application defects.
D. Skip Test Cases
@Test
public void skipTest() {
throw new SkipException(
"Skipping test due to environment issue");
}
E. Test Dependencies
@Test
public void createUser() {
System.out.println("User created");
}
@Test(dependsOnMethods = "createUser")
public void updateUser() {
System.out.println("User updated");
}
@Test(dependsOnMethods = "updateUser")
public void deleteUser() {
System.out.println("User deleted");
}
32. Selenium Framework Best Practices
| Area | Recommended Practice |
|---|---|
| Driver management | ThreadLocal WebDriver |
| Test design | Independent test cases |
| Page design | Page Object Model |
| Locators | Prefer stable IDs and test attributes |
| Waits | Explicit waits |
| Test data | Separate data from test logic |
| Configuration | Properties and environment variables |
| Secrets | Environment variables or CI secret store |
| Reporting | Extent Reports and TestNG XML |
| Logging | Log4j2 |
| Screenshots | Capture on failure |
| Parallel testing | TestNG parallel execution |
| CI/CD | Jenkins or GitHub Actions |
| Version control | Git |
| Code quality | Checkstyle or Spotless |
| Browser execution | Local and Selenium Grid |
Recommended Additional Improvements
- Add API-based test data setup to reduce UI dependencies.
- Add a database utility if tests require database verification.
- Integrate REST Assured for API testing.
- Use Selenium Grid or Docker Selenium for remote execution.
- Use separate configuration files for QA, staging and production.
- Add environment-specific reporting.
- Add automatic cleanup of test-created data.
- Use Allure or Extent Reports for richer reporting.
- Add code-quality checks to the Maven pipeline.
- Add consistent failure classification and retry policies.
33. Expected Execution Reports
selenium-testng-maven/
|
|-- target/
| |-- surefire-reports/
| |-- TEST-com.automation.tests.LoginTest.xml
| |-- com.automation.tests.LoginTest.txt
| |-- testng-results.xml
|
|-- reports/
| |-- ExtentReport.html
|
|-- screenshots/
| |-- failedTest_20261127_120000_000.png
|
|-- logs/
|-- automation.log
| Report | Location |
|---|---|
| TestNG XML | target/surefire-reports/ |
| TestNG text | target/surefire-reports/ |
| Extent HTML | reports/ExtentReport.html |
| Screenshots | screenshots/ |
| Log4j2 logs | logs/automation.log |
Open the Extent report in a browser using reports/ExtentReport.html.
TestNG and Surefire generate their own reports. Extent Reports is generated by the custom listener.
34. Troubleshooting Common Problems
| Problem | Solution |
|---|---|
| WebDriver executable not found | Check driver management and browser installation |
| Maven dependencies not downloaded | Run mvn clean install |
| TestNG tests not executing | Verify testng.xml and Surefire configuration |
| Chrome not opening in CI | Enable headless mode |
| Stale element exception | Re-locate elements |
| Timeout exception | Verify locator and wait condition |
| Parallel tests interfering | Use ThreadLocal and isolated test data |
| Extent report empty | Verify listener registration and flush() |
| Screenshot not captured | Ensure driver is alive when capturing |
| Browser version mismatch | Update browser and driver management |
Important Implementation Checks
- Register TestListener only once.
- Capture failure screenshots before quitting the browser.
- Add commons-io dependency for FileUtils if using that API.
- Configure Maven properties with defaults.
- Avoid competing browser configuration mechanisms.
- Use unique report directories when running multiple Maven forks.
35. Complete Framework Execution Workflow
- Maven reads pom.xml: Resolves Selenium, TestNG, WebDriverManager and reporting dependencies.
- TestNG reads testng.xml: Identifies test classes, groups and parallel execution configuration.
- BaseTest initializes WebDriver: DriverFactory creates a browser instance for the current thread.
- Page Object Model executes: Page classes interact with the application.
- TestNG assertions validate results: Hard and soft assertions determine test outcomes.
- Listeners capture results: Failure screenshots and Extent test details are recorded.
- Browser cleanup: WebDriver sessions are closed and ThreadLocal values removed.
- Reports generated: TestNG XML, Surefire results, Extent HTML and logs are saved.
36. Selenium + TestNG + Maven Interview Questions
- What is the difference between Selenium WebDriver and Selenium Grid?
- What is the difference between TestNG and JUnit?
- Explain the TestNG annotation execution lifecycle.
- What is the difference between @BeforeTest and @BeforeMethod?
- How does TestNG parallel execution work?
- Why do we use ThreadLocal WebDriver?
- What is the difference between parallel="classes" and parallel="methods"?
- What is the difference between DataProvider and Parameters?
- Explain TestNG Factory with an example.
- How do you implement RetryAnalyzer?
- How do you capture screenshots on failure?
- How do you implement Extent Reports with TestNG?
- What is the difference between Maven Surefire and Failsafe?
- Explain Maven lifecycle phases.
- How do you run specific groups using Maven?
- How do you execute Selenium tests in headless mode?
- How do you execute cross-browser tests?
- How do you handle stale element exceptions?
- How do you manage test data in an automation framework?
- How do you integrate Selenium with Jenkins?
- How do you execute Selenium tests using Docker?
- How do you manage browser sessions in parallel execution?
- How do you implement a reusable Page Object Model?
- How do you integrate API testing with UI automation?
- How do you design a scalable automation framework?
37. Useful Selenium + TestNG + Maven Resources
38. Final Recommended Enterprise Framework Architecture
Selenium + TestNG + Maven
|
|-- Page Object Model
|-- ThreadLocal WebDriver
|-- Test Data Management
|-- API Testing (REST Assured)
|-- Database Validation
|-- TestNG Listeners
|-- Extent / Allure Reports
|-- Log4j2
|-- Selenium Grid / Docker
|-- Jenkins / GitHub Actions
|-- Code Quality (Spotless)
This architecture provides a strong foundation for enterprise-level automation, cross-browser testing, parallel execution and CI/CD integration.

No comments:
Post a Comment