Selenium/Healenium

Introduction to Selenium WebDriver

Selenium WebDriver is one of the most popular tools for automating web applications for testing purposes. It allows you to simulate real user interactions with a browser, such as clicking buttons, entering text, and navigating through pages. It’s open-source, supports multiple programming languages like Java, Python, C#, and works with major browsers such as Chrome, Firefox, Safari, and Edge.

What is Selenium?

Selenium is a suite of tools that support browser automation. The core components include:
โ€ข Selenium IDE โ€“ A record-and-playback tool for simple tests
โ€ข Selenium RC โ€“ A deprecated server-based tool (replaced by WebDriver)
โ€ข Selenium WebDriver โ€“ The most powerful and flexible tool
โ€ข Selenium Grid โ€“ Used for running tests on different machines in parallel

Why Use Selenium WebDriver?

  • โ€ข Open-source and free to use
  • โ€ข Supports multiple languages (Java, Python, C#, Ruby, etc.)
  • โ€ข Cross-browser support (Chrome, Firefox, Edge, Safari)
  • โ€ข Platform-independent (Windows, macOS, Linux)
  • โ€ข Easy integration with tools like Maven, Jenkins, TestNG, and Cucumber

How Selenium WebDriver Works

Selenium WebDriver uses browser-specific drivers (like ChromeDriver or GeckoDriver) to interact with the browser. It sends commands to the browser and retrieves results using the JSON Wire Protocol (or W3C WebDriver standard).

[Insert Image: Diagram showing WebDriver โ†’ Browser Driver โ†’ Real Browser]

Basic Selenium WebDriver Script in Java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyTest {
ย  public static void main(String[] args) {
ย ย ย  System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
ย ย ย  WebDriver driver = new ChromeDriver();
ย ย ย  driver.get(“https://example.com”);
ย ย ย  System.out.println(driver.getTitle());
ย ย ย  driver.quit();
ย  }
}

Important Interfaces in Selenium WebDriver

  • โ€ข WebDriver โ€“ Main interface controlling the browser
  • โ€ข WebElement โ€“ Represents an HTML element
  • โ€ข By โ€“ Used to locate elements (e.g., By.id, By.xpath)

Summary

Selenium WebDriver is a powerful tool for web UI automation. It enables you to simulate a userโ€™s actions in a browser and is the foundation for building robust automated test frameworks.

[Insert Image: Screenshot of Selenium test running in Chrome]

Selenium for Beginners โ€“ Page 2

JUnit Framework for Java Testers

JUnit is a widely used testing framework for Java. It provides annotations, assertions, and tools that help developers and QA engineers write repeatable, reliable unit tests. JUnit is the foundation for test automation in Java-based Selenium projects. Understanding JUnit is essential to organize and manage automated tests efficiently.

Why Use JUnit?

  • โ€ข Easy to learn and integrate into Java projects
  • โ€ข Provides annotations for controlling test execution
  • โ€ข Helps in grouping, executing, and reporting test results
  • โ€ข Works well with Selenium and build tools like Maven
  • โ€ข Highly compatible with CI/CD pipelines like Jenkins

Common JUnit Annotations

  • @Test โ€“ Marks a method as a test case
  • @Before โ€“ Runs before each test
  • @After โ€“ Runs after each test
  • @BeforeClass โ€“ Runs once before any test methods
  • @AfterClass โ€“ Runs once after all tests are complete
  • @Ignore โ€“ Skips the test method

Simple JUnit Test Example

import org.junit.Test;
import static org.junit.Assert.*;

public class CalculatorTest {
ย  @Test
ย  public void testAddition() {
ย ย ย  int result = 2 + 3;
ย ย ย  assertEquals(5, result);
ย  }
}

JUnit with Selenium WebDriver

You can use JUnit to organize Selenium tests. A typical Selenium test class would include setup, test, and teardown methods to open a browser, execute actions, and close the browser.

[Insert Image: Lifecycle diagram โ€“ BeforeClass โ†’ Before โ†’ Test โ†’ After โ†’ AfterClass]

Useful Assertions

  • โ€ข assertEquals(expected, actual)
  • โ€ข assertTrue(condition)
  • โ€ข assertFalse(condition)
  • โ€ข assertNotNull(object)
  • โ€ข assertArrayEquals(expectedArray, resultArray)

Summary

JUnit provides a structured way to write, manage, and report unit tests in Java. Itโ€™s lightweight and integrates smoothly with Selenium and other tools, making it perfect for writing maintainable automation scripts.

TestNG Framework Essentials

TestNG (Test Next Generation) is a powerful testing framework inspired by JUnit but with more advanced capabilities. It is widely used in automation frameworks, especially with Selenium WebDriver, due to its flexibility in managing test execution, prioritization, grouping, and data-driven testing. TestNG also integrates seamlessly with build tools like Maven and CI tools like Jenkins.

Why Choose TestNG for Selenium?

  • โ€ข Allows test grouping and prioritization
  • โ€ข Supports parallel test execution
  • โ€ข Enables parameterized testing via XML or @DataProvider
  • โ€ข Provides detailed HTML reports by default
  • โ€ข Supports configuration annotations beyond @Test

Key TestNG Annotations

  • @BeforeSuite โ€“ Executes before all tests in the suite
  • @AfterSuite โ€“ Executes after all tests in the suite
  • @BeforeClass / @AfterClass โ€“ Executes once per test class
  • @BeforeMethod / @AfterMethod โ€“ Executes before and after each @Test
  • @Test โ€“ Marks the test method

TestNG Example with Selenium

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class LoginTest {
ย  WebDriver driver;

ย  @BeforeMethod
ย  public void setUp() {
ย ย ย  System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
ย ย ย  driver = new ChromeDriver();
ย  }

ย  @Test
ย  public void login() {
ย ย ย  driver.get(“https://example.com/login”);
ย ย ย  // perform login steps
ย  }

ย  @AfterMethod
ย  public void tearDown() {
ย ย ย  driver.quit();
ย  }
}

TestNG Suite XML Configuration

<suite name=”AllTests”>
ย  <test name=”LoginTests”>
ย ย ย  <classes>
ย ย ย ย ย  <class name=”LoginTest”/>
ย ย ย  </classes>
ย  </test>
</suite>

Summary

TestNG is a highly extensible and feature-rich testing framework that enhances Selenium test organization. Its configuration options, powerful annotations, and rich reporting make it ideal for professional-grade automation frameworks.

Selenium for Beginners โ€“ Page 4

Maven for Test Automation Projects

Maven is a powerful build automation and dependency management tool primarily used in Java projects. In test automation, it helps in managing libraries like Selenium, TestNG, and others efficiently. With Maven, you define project structure, manage plugins, and configure dependencies all from a single `pom.xml` file.

Why Use Maven in Selenium Projects?

  • โ€ข Automatically downloads and manages JAR dependencies
  • โ€ข Simplifies project build and execution
  • โ€ข Provides a consistent project structure
  • โ€ข Supports plugins for reporting, test execution, code analysis, etc.
  • โ€ข Integrates well with CI/CD tools like Jenkins

Standard Maven Project Structure

  • project-name/
  • โ”œโ”€โ”€ src/
  • โ”‚ย ย  โ”œโ”€โ”€ main/java/
  • โ”‚ย ย  โ””โ”€โ”€ test/java/
  • โ”œโ”€โ”€ pom.xml
  • โ””โ”€โ”€ target/

Understanding pom.xml

The `pom.xml` (Project Object Model) is the core file of any Maven project. It defines project metadata, dependencies, plugins, and build configuration.

Example: Adding Selenium and TestNG

<dependencies>
ย  <dependency>
ย ย ย  <groupId>org.seleniumhq.selenium</groupId>
ย ย ย  <artifactId>selenium-java</artifactId>
ย ย ย  <version>4.1.0</version>
ย  </dependency>
ย  <dependency>
ย ย ย  <groupId>org.testng</groupId>
ย ย ย  <artifactId>testng</artifactId>
ย ย ย  <version>7.4.0</version>
ย ย ย  <scope>test</scope>
ย  </dependency>
</dependencies>

Common Maven Commands

  • โ€ข `mvn clean` โ€“ Cleans previous builds
  • โ€ข `mvn compile` โ€“ Compiles the project
  • โ€ข `mvn test` โ€“ Runs the test cases
  • โ€ข `mvn package` โ€“ Builds the project into a JAR or WAR file
  • โ€ข `mvn install` โ€“ Installs project into local repository

Summary

Maven simplifies Java automation projects by managing dependencies, standardizing structure, and supporting automation scripts. It’s a must-know tool for QA engineers working with Java and Selenium.

Selenium for Beginners โ€“ Page 5

Page Object Model (POM) in Selenium

Page Object Model (POM) is a design pattern used in Selenium automation to improve the maintainability and readability of test scripts. In POM, each web page is represented as a separate class, containing locators (web elements) and methods (actions). This structure allows for better separation of test logic and UI structure.

Why Use Page Object Model?

  • โ€ข Increases reusability of code across multiple tests
  • โ€ข Simplifies maintenance as UI changes only need updates in one class
  • โ€ข Improves readability and organization
  • โ€ข Makes debugging and enhancements easier

Basic Structure of POM

A POM framework typically contains:
โ€ข Page Classes โ€“ One per webpage, includes element locators and actions
โ€ข Test Classes โ€“ Use page classes to drive tests
โ€ข Base Class โ€“ Common functions (like opening browser)
โ€ข Utility Classes โ€“ Additional support functions like reading data from files

Example: LoginPage.java

public class LoginPage {
ย  WebDriver driver;

ย  @FindBy(id=”username”)
ย  WebElement username;

ย  @FindBy(id=”password”)
ย  WebElement password;

ย  @FindBy(id=”login”)
ย  WebElement loginButton;

ย  public LoginPage(WebDriver driver) {
ย ย ย  this.driver = driver;
ย ย ย  PageFactory.initElements(driver, this);
ย  }

ย  public void login(String user, String pass) {
ย ย ย  username.sendKeys(user);
ย ย ย  password.sendKeys(pass);
ย ย ย  loginButton.click();
ย  }
}

Why Use PageFactory?

  • โ€ข Simplifies element initialization
  • โ€ข Supports annotations like @FindBy
  • โ€ข Reduces repetitive code
  • โ€ข Makes tests more robust

Test Class Example

public class LoginTest {
ย  WebDriver driver;

ย  @BeforeMethod
ย  public void setUp() {
ย ย ย  driver = new ChromeDriver();
ย ย ย  driver.get(“https://example.com”);
ย  }

ย  @Test
ย  public void verifyLogin() {
ย ย ย  LoginPage login = new LoginPage(driver);
ย ย ย  login.login(“testuser”, “password”);
ย  }

ย  @AfterMethod
ย  public void tearDown() {
ย ย ย  driver.quit();
ย  }
}

Summary

Page Object Model provides a robust and scalable design for building automation frameworks. It separates the structure of the web pages from the test logic, reducing redundancy and making automation scripts more maintainable.

Selenium for Beginners โ€“ Page 6

Understanding Locators in Selenium

Locators are the foundation of every Selenium WebDriver test. They allow you to find and interact with web elements like buttons, input fields, checkboxes, and links. Choosing the right locator is crucial for building stable and reliable test automation.

What Are Locators?

A locator tells Selenium how to find an element on the webpage. Selenium provides various types of locators to accommodate different HTML structures and scenarios.

Types of Selenium Locators

  • โ€ข By ID โ€“ driver.findElement(By.id(“username”))
  • โ€ข By Name โ€“ driver.findElement(By.name(“email”))
  • โ€ข By Class Name โ€“ driver.findElement(By.className(“btn-primary”))
  • โ€ข By Tag Name โ€“ driver.findElement(By.tagName(“input”))
  • โ€ข By Link Text โ€“ driver.findElement(By.linkText(“Click here”))
  • โ€ข By Partial Link Text โ€“ driver.findElement(By.partialLinkText(“Click”))
  • โ€ข By CSS Selector โ€“ driver.findElement(By.cssSelector(“input[type=’text’]”))
  • โ€ข By XPath โ€“ driver.findElement(By.xpath(“//input[@id=’password’]”))

Best Practices for Using Locators

  • โ€ข Prefer ID over other locators (fastest and most stable)
  • โ€ข Avoid brittle XPaths that rely on positions
  • โ€ข Use descriptive class names and data attributes if available
  • โ€ข Use CSS selectors for speed and flexibility
  • โ€ข Ensure locators are unique on the page

Locator Examples in Java

WebElement loginButton = driver.findElement(By.id(“login”));
WebElement emailField = driver.findElement(By.cssSelector(“input[type=’email’]”));
WebElement forgotPassword = driver.findElement(By.linkText(“Forgot Password?”));

XPath vs CSS: When to Use Which?

โ€ข Use CSS for performance and simplicity
โ€ข Use XPath when you need to traverse the DOM (parent/sibling/ancestor relationships)
โ€ข Avoid overly long or brittle paths in either method

Summary

Locators are essential for identifying elements on a webpage. Mastering all types of locators gives you the flexibility to write strong, reliable automation scripts for any application.

Selenium for Beginners โ€“ Page 7

Handling Waits in Selenium

Handling timing issues in web applications is one of the key responsibilities of a QA automation engineer. Elements may not appear instantly after a page loads, and without waits, your test scripts might fail unexpectedly. Selenium WebDriver provides different types of waits to synchronize test execution with web element rendering.

Types of Waits in Selenium

There are three major types of waits used in Selenium:

  • โ€ข Implicit Wait โ€“ Sets a global wait time for all elements. It tells WebDriver to wait for a specified time before throwing an exception.
  • โ€ข Explicit Wait โ€“ Waits for a specific condition to be met for a particular element before continuing.
  • โ€ข Fluent Wait โ€“ Similar to Explicit Wait but allows customization such as polling frequency and exception handling.

Implicit Wait Example

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// Applies to all findElement calls

Explicit Wait Example

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“submit”)));

Fluent Wait Example

Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
ย  .withTimeout(Duration.ofSeconds(20))
ย  .pollingEvery(Duration.ofSeconds(2))
ย  .ignoring(NoSuchElementException.class);

WebElement element = fluentWait.until(driver -> driver.findElement(By.id(“username”)));

When to Use Each Type?

โ€ข Use **Implicit Wait** for simple applications where delays are predictable.
โ€ข Use **Explicit Wait** for elements that load conditionally.
โ€ข Use **Fluent Wait** when you need advanced customization.

Best Practices for Using Waits

  • โ€ข Do not use Thread.sleep() โ€“ itโ€™s a fixed wait and slows down tests unnecessarily.
  • โ€ข Use Explicit Waits for dynamic content and AJAX calls.
  • โ€ข Donโ€™t mix Implicit and Explicit waits together.
  • โ€ข Use Fluent Wait when you need polling and exception handling.

Summary

Waits are critical in Selenium to ensure your scripts work reliably with dynamic web applications. Choosing the right type of wait helps your automation be both efficient and stable.

Selenium for Beginners โ€“ Page 8

Test Driven Development (TDD) for QA

Test Driven Development (TDD) is a software development approach where tests are written before the actual code. It helps ensure that the system is built according to expectations and that it passes defined requirements from the start. In the QA world, understanding TDD enhances collaboration with developers and helps improve the structure and coverage of tests.

What is TDD?

TDD is a development process that revolves around the **Red-Green-Refactor** cycle:
1. Write a failing test (Red)
2. Write the minimum code required to make the test pass (Green)
3. Refactor the code for efficiency (Refactor)

Benefits of TDD in QA and Automation

  • โ€ข Ensures better understanding of feature requirements
  • โ€ข Catches bugs early during the development cycle
  • โ€ข Leads to modular, flexible, and maintainable code
  • โ€ข Improves communication between QA and developers
  • โ€ข Results in better test coverage and cleaner code

TDD Example: Login Function

1. Write test first:
@Test
public void testLogin() {
ย  User user = new User();
ย  assertTrue(user.login(“admin”, “1234”));
}

2. Create dummy class with method:
public class User {
ย  public boolean login(String u, String p) {
ย ย ย  return true; // Dummy logic to make test pass
ย  }
}

3. Refactor with real logic later

How QA Can Apply TDD Principles

โ€ข Start by writing tests for UI elements or API endpoints before development starts.
โ€ข Collaborate with developers using shared BDD or Gherkin scenarios.
โ€ข Build automation frameworks to support evolving test suites.
โ€ข Use tools like JUnit or TestNG to drive development with tests.

Common Misunderstandings About TDD

โ€ข TDD doesnโ€™t mean you write all tests first, but that each piece of code is guided by a test.
โ€ข TDD is not just for developers; QA can help define and review test logic.
โ€ข TDD doesnโ€™t eliminate the need for other testing types like exploratory or integration.

Summary

TDD empowers teams to build software that is both reliable and maintainable. QA professionals who understand TDD principles can participate earlier in the development cycle and help create more meaningful automated tests.

Selenium for Beginners โ€“ Page 9

Behavior Driven Development (BDD) & Cucumber

Behavior Driven Development (BDD) is an agile testing practice that emphasizes collaboration between developers, testers, and business stakeholders. It focuses on the behavior of software from the userโ€™s perspective using natural language.

What is BDD?

BDD is built on the foundation of Test Driven Development (TDD), but uses a more readable and collaborative format. BDD encourages writing tests in a natural, English-like language that everyone can understand.

Key BDD Concepts

  • โ€ข Scenarios โ€“ Specific behavior or interaction to test
  • โ€ข Given โ€“ Precondition or setup
  • โ€ข When โ€“ The action or trigger
  • โ€ข Then โ€“ Expected result or outcome

Cucumber Feature File Example

Feature: Login functionality

Scenario: Successful login with valid credentials
ย  Given user is on login page
ย  When user enters valid username and password
ย  Then user should be redirected to the homepage

What is Cucumber?

Cucumber is a popular BDD tool that supports writing feature files in Gherkin syntax. It acts as a bridge between plain English test cases and executable code. In Java projects, it is commonly used with Selenium and TestNG.

Steps to Implement BDD with Cucumber in Selenium

  • โ€ข Create a Maven project and add Cucumber dependencies
  • โ€ข Write Gherkin feature files (*.feature) under `src/test/resources`
  • โ€ข Create Step Definitions that map feature steps to Java code
  • โ€ข Create a Runner class with @CucumberOptions
  • โ€ข Use Page Object Model for step implementations

Advantages of Using BDD

  • โ€ข Encourages collaboration between technical and non-technical teams
  • โ€ข Improves test readability and reusability
  • โ€ข Ensures better requirement understanding
  • โ€ข Keeps automation aligned with business behavior

Summary

BDD and Cucumber help bridge the gap between development and business logic by enabling tests written in a language that everyone understands. It promotes better collaboration, clarity, and traceability for all stakeholders.

Selenium for Beginners โ€“ Page 10

Excel Data Handling in Selenium

In real-world test automation scenarios, especially for data-driven testing, it is common to read data from Excel files. This allows testers to separate test data from test logic and run the same test multiple times with different input data.

Libraries Used in Java for Excel Handling

โ€ข Apache POI โ€“ Most widely used library for reading/writing Microsoft Excel files (XLS and XLSX formats).
โ€ข JExcelAPI โ€“ Legacy library that supports XLS files (not XLSX). Less used nowadays.

Add Apache POI to pom.xml

<dependency>
ย  <groupId>org.apache.poi</groupId>
ย  <artifactId>poi-ooxml</artifactId>
ย  <version>5.2.2</version>
</dependency>

Example: Reading Data from Excel

FileInputStream fis = new FileInputStream(“data.xlsx”);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet(“Sheet1”);
String value = sheet.getRow(0).getCell(0).getStringCellValue();
System.out.println(“Cell value: ” + value);
workbook.close();

Example: Writing to Excel File

FileOutputStream fos = new FileOutputStream(“data.xlsx”);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(“Result”);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(“Passed”);
workbook.write(fos);
workbook.close();

Best Practices for Excel Handling

  • โ€ข Always close FileInputStream and Workbook to avoid memory leaks
  • โ€ข Use try-catch-finally blocks or try-with-resources
  • โ€ข Keep Excel files in `src/test/resources` for easy access
  • โ€ข Validate data format before parsing (e.g., check if numeric or string)

Use Cases for Excel in Testing

  • โ€ข Data-driven testing (DDT) where multiple inputs are needed
  • โ€ข Test result reporting
  • โ€ข Configuration file for test inputs
  • โ€ข Maintaining large data sets for form inputs or validations

Summary

Excel handling using Apache POI gives automation testers powerful tools to support data-driven frameworks. It enables flexibility and efficiency in writing scalable tests by allowing input and output from external files.







Selenium for Beginners โ€“ Page 11

File Handling in Java for Test Automation

File handling is an essential part of many test automation projects. It allows you to create, read, write, update, or delete files that are often required for reading input data or writing logs and test results. In Java, file operations are provided by the java.io and java.nio.file packages.

Common File Handling Operations

These are the most frequently used file operations in Java automation:

  • โ€ข Creating a file
  • โ€ข Writing to a file
  • โ€ข Reading from a file
  • โ€ข Deleting a file
  • โ€ข Checking file existence

Creating a File

try {
ย  File myFile = new File(“testdata.txt”);
ย  if (myFile.createNewFile()) {
ย ย ย  System.out.println(“File created: ” + myFile.getName());
ย  } else {
ย ย ย  System.out.println(“File already exists.”);
ย  }
} catch (IOException e) {
ย  e.printStackTrace();
}

Writing to a File

try {
ย  FileWriter writer = new FileWriter(“testdata.txt”);
ย  writer.write(“Test data goes here”);
ย  writer.close();
ย  System.out.println(“Successfully wrote to the file.”);
} catch (IOException e) {
ย  e.printStackTrace();
}

Reading from a File

try {
ย  File myFile = new File(“testdata.txt”);
ย  Scanner reader = new Scanner(myFile);
ย  while (reader.hasNextLine()) {
ย ย ย  String data = reader.nextLine();
ย ย ย  System.out.println(data);
ย  }
ย  reader.close();
} catch (FileNotFoundException e) {
ย  e.printStackTrace();
}

Deleting a File

File myFile = new File(“testdata.txt”);
if (myFile.delete()) {
ย  System.out.println(“Deleted the file: ” + myFile.getName());
} else {
ย  System.out.println(“Failed to delete the file.”);
}

Usage in Selenium Projects

  • โ€ข Saving test run logs to a file
  • โ€ข Reading test data for data-driven testing
  • โ€ข Writing test outcomes for reporting
  • โ€ข Generating screenshots or HTML reports
  • โ€ข Downloading files and verifying their contents

Best Practices for File Handling

  • โ€ข Always close file readers/writers to avoid memory leaks.
  • โ€ข Use try-with-resources to handle closing automatically.
  • โ€ข Keep files organized under resource or output directories.
  • โ€ข Validate file existence before attempting to read/write.

Summary

Mastering file handling in Java enables better control over input/output in test automation. It is especially useful in reading data, exporting test results, and managing files created during automation.

Selenium for Beginners โ€“ Page 12

JDBC for Test Automation in Java

JDBC (Java Database Connectivity) is an API in Java that allows you to connect and interact with relational databases such as MySQL, PostgreSQL, SQL Server, and Oracle. In test automation, JDBC is valuable for validating backend data, verifying test results, and managing test setup/teardown data.

What is JDBC?

JDBC provides classes and interfaces for:
โ€ข Establishing a database connection
โ€ข Executing SQL queries
โ€ข Reading result sets
โ€ข Closing connections

JDBC Architecture

JDBC uses a 4-step process:
1. Load the JDBC driver
2. Establish the database connection
3. Create a statement and execute SQL
4. Process the results and close the connection

Example: Connecting to MySQL Database

import java.sql.*;

public class DBTest {
ย  public static void main(String[] args) throws Exception {
ย ย ย  Class.forName(“com.mysql.cj.jdbc.Driver”);
ย ย ย  Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydb”, “user”, “password”);
ย ย ย  Statement stmt = conn.createStatement();
ย ย ย  ResultSet rs = stmt.executeQuery(“SELECT * FROM users”);
ย ย ย  while (rs.next()) {
ย ย ย ย ย  System.out.println(rs.getString(“username”));
ย ย ย  }
ย ย ย  conn.close();
ย  }
}

Maven Dependency for MySQL Connector

<dependency>
ย  <groupId>mysql</groupId>
ย  <artifactId>mysql-connector-java</artifactId>
ย  <version>8.0.33</version>
</dependency>

Where JDBC Helps in Automation

  • โ€ข Verifying data inserted via UI is saved correctly in DB
  • โ€ข Cleaning up test data after test execution
  • โ€ข Reading credentials or configurations from DB
  • โ€ข Creating reports directly from SQL queries
  • โ€ข Performing complex validations that UI cannot expose

JDBC Best Practices

  • โ€ข Always close ResultSet, Statement, and Connection to free resources.
  • โ€ข Use try-with-resources for auto-closing JDBC objects.
  • โ€ข Avoid hardcoding credentials; use environment variables.
  • โ€ข Use parameterized queries to prevent SQL injection.
  • โ€ข Log and handle exceptions properly.

JDBC Integration with Selenium

Selenium can be combined with JDBC to validate data integrity:
1. Fill and submit a form using Selenium
2. Use JDBC to verify the data in the database
3. Report mismatches or log success

This ensures full end-to-end testing from UI to backend.

Summary

JDBC is a vital tool for automation testers working on database-integrated systems. It gives visibility into the backend and enables strong verification and data-driven strategies.

Selenium for Beginners โ€“ Page 13

Advanced XPath & CSS Selectors in Selenium

Locating elements precisely and reliably is a crucial part of Selenium automation. While basic locators like ID or name are straightforward, advanced scenarios require powerful selectors like XPath and CSS. This guide dives into advanced strategies for using XPath and CSS selectors effectively.

Understanding XPath

XPath (XML Path Language) is used to navigate through elements and attributes in an XML or HTML document. Selenium supports XPath 1.0, which is sufficient for most web applications.

Absolute vs Relative XPath

โ€ข Absolute XPath: Starts from root (e.g., /html/body/div[2]/form/input)
โ€ข Relative XPath: Starts from anywhere (e.g., //input[@type=’submit’])
Relative XPath is preferred for maintainability and flexibility.

Useful XPath Functions

  • โ€ข `contains(text(), ‘Login’)` โ€“ Matches partial text
  • โ€ข `starts-with(@id, ‘btn’)` โ€“ Matches attribute prefix
  • โ€ข `text()` โ€“ Selects element by visible text
  • โ€ข `@*` โ€“ Matches any attribute
  • โ€ข `ancestor::`, `preceding::`, `following-sibling::` โ€“ Axis for navigation

Advanced XPath Examples

//div[@class=’login-form’]//input[@type=’text’]
//a[contains(text(),’Forgot’)]
//ul/li[last()] โ€“ Selects the last list item
//input[@type=’text’ and @name=’username’]

CSS Selector Overview

CSS (Cascading Style Sheets) selectors are faster and more readable than XPath in many cases. Selenium supports full CSS3 selectors.

  • โ€ข `tag#id` โ€“ e.g., input#username
  • โ€ข `.class` โ€“ e.g., button.submit
  • โ€ข `[attribute=’value’]` โ€“ e.g., input[name=’email’]
  • โ€ข `tag:nth-child(n)` โ€“ e.g., ul li:nth-child(2)
  • โ€ข `tag1 > tag2` โ€“ direct child selector

XPath vs CSS โ€“ When to Use What?

  • โ€ข XPath supports backward navigation (e.g., parent, ancestor) while CSS doesnโ€™t.
  • โ€ข CSS selectors are generally faster in performance.
  • โ€ข XPath is more flexible for complex DOM structures.
  • โ€ข Use CSS for speed, XPath for flexibility.

Best Practices for Using Selectors

  • โ€ข Avoid absolute XPath as it breaks with layout changes.
  • โ€ข Prefer IDs or data-* attributes when available.
  • โ€ข Keep selectors short and readable.
  • โ€ข Use browser developer tools (F12) to test and build selectors.
  • โ€ข Use relative XPath for robust, maintainable tests.

Summary

Mastering XPath and CSS selectors empowers testers to locate and interact with elements across any application. Use browser inspection tools to craft strong locators and choose the best strategy depending on your use case.

Selenium for Beginners โ€“ Page 14

Creating and Using Methods in Selenium with Java

In Java-based Selenium automation, methods help structure your code into reusable blocks. They make your test scripts cleaner, modular, and easier to maintain. This guide explains how to create, call, and organize methods for efficient test automation.

What is a Method in Java?

A method is a block of code that performs a specific task. It can accept inputs (parameters) and return outputs. Java methods reduce duplication and allow us to define clear steps in a test case.

Types of Methods in Selenium Projects

There are two broad types:

  • โ€ข Utility Methods โ€“ for common tasks like clicking, sending text, verifying elements.
  • โ€ข Test Methods โ€“ written with @Test annotation (e.g., TestNG) for defining test cases.

Syntax of a Method in Java

public returnType methodName(parameters) {
ย ย ย  // method body
ย ย ย  return value;
}

Example: Utility Method for Clicking

public void clickElement(By locator) {
ย ย ย  driver.findElement(locator).click();
}

Example: Method to Type Text

public void enterText(By locator, String text) {
ย ย ย  driver.findElement(locator).sendKeys(text);
}

public String getElementText(By locator) {
ย ย ย  return driver.findElement(locator).getText();
}

How to Call a Method

You can call the method from your test class or another method:
clickElement(By.id(“loginBtn”));
enterText(By.name(“email”), “test@example.com”);

Using Methods in POM Structure

  • โ€ข Create separate Page Classes for each page (LoginPage, DashboardPage, etc.)
  • โ€ข Add element locators and actions as methods inside those classes
  • โ€ข Call them in your test class for reuse and clean code structure

Best Practices for Methods

  • โ€ข Use descriptive method names (e.g., `clickLoginButton()` instead of `click1()`)
  • โ€ข Keep method size short and focused on one action
  • โ€ข Use parameters to make methods flexible and reusable
  • โ€ข Group related methods in utility classes or base test classes
  • โ€ข Avoid hardcoding values inside methods

Summary

Creating and organizing methods is a foundational skill in Java Selenium automation. It improves reusability, test readability, and framework scalability. Structure your tests using methods for better debugging and code maintenance.

Selenium for Beginners โ€“ Page 15

Understanding Selenium Hierarchy and Architecture

To become a skilled automation engineer, it’s essential to understand how Selenium is structured. This page provides a clear overview of the Selenium tool hierarchy, its architecture, and the relationship between its components like WebDriver, Selenium Grid, and IDE.

What is Selenium?

Selenium is a suite of open-source tools that automate web browsers. It is widely used for end-to-end UI testing and supports multiple programming languages and browsers.

Selenium Tool Suite

The Selenium suite consists of the following tools:

  • โ€ข Selenium IDE โ€“ A record and playback tool for simple tests.
  • โ€ข Selenium WebDriver โ€“ Core tool for writing browser-agnostic automation code.
  • โ€ข Selenium Grid โ€“ Allows parallel test execution across machines and browsers.

Selenium WebDriver Hierarchy

Here’s how the WebDriver hierarchy looks:

  • โ€ข WebDriver (Interface) โ€“ Root interface for browser drivers
  • ย ย ย โ†ณ RemoteWebDriver โ€“ Implements WebDriver methods
  • ย ย ย ย ย ย ย โ†ณ ChromeDriver, FirefoxDriver, EdgeDriver, SafariDriver โ€“ Concrete implementations for each browser

WebDriver Architecture

Selenium WebDriver follows a client-server architecture. The automation script communicates with the browser driver, which in turn controls the browser. Here’s the flow:

  1. 1. Test script sends HTTP requests (commands) to the browser driver
  2. 2. Browser driver converts requests into browser-native commands
  3. 3. Browser performs the actions (e.g., click, type)
  4. 4. Response is sent back to the test script

Supported Browser Drivers

  • โ€ข ChromeDriver โ€“ For Google Chrome
  • โ€ข GeckoDriver โ€“ For Mozilla Firefox
  • โ€ข EdgeDriver โ€“ For Microsoft Edge
  • โ€ข SafariDriver โ€“ For Safari (macOS only)

Selenium Grid Architecture

Selenium Grid allows running tests in parallel on different machines (nodes). It consists of a central hub and multiple nodes:
โ€ข Hub โ€“ Receives test requests and distributes them to nodes.
โ€ข Node โ€“ Executes test cases on the configured browser and OS.

Integration with Frameworks and Tools

  • โ€ข TestNG / JUnit โ€“ Testing frameworks to manage test execution
  • โ€ข Maven / Gradle โ€“ Build tools for dependency management
  • โ€ข Jenkins โ€“ CI/CD for scheduling and monitoring tests
  • โ€ข Git โ€“ Version control for source code collaboration

Summary

Seleniumโ€™s modular design lets you build scalable and flexible automation frameworks. Understanding how its tools and drivers fit together helps you troubleshoot better and create optimized test scripts.

Selenium for Beginners โ€“ Page 16

Understanding Hierarchies in Selenium: POM, XPath, and OOP Concepts

This guide covers the structural hierarchies that influence Selenium test automation. We will explore the hierarchy of Page Object Model (POM), XPath, and Object-Oriented Programming (OOP) concepts as they apply to automation frameworks.

Page Object Model (POM) Hierarchy

POM is a design pattern that promotes maintainability by separating UI object logic from test logic. It involves structured layers for clarity and reuse.

  • โ€ข Base Class โ€“ Contains shared setup, teardown, and common utilities
  • โ€ข Page Classes โ€“ Represent individual pages (LoginPage, HomePage, etc.) with WebElements and methods
  • โ€ข Test Classes โ€“ Contain @Test methods, calling actions from Page Classes
  • โ€ข Utilities โ€“ Separate reusable libraries (e.g., ExcelReader, DBUtils)


Visual Layout:

ย  TestClass.java
ย ย ย  โ†ณ LoginPage.java
ย ย ย ย ย ย ย  โ†ณ BasePage.java
ย ย ย ย ย ย ย  โ†ณ WebDriverUtils.java
ย ย ย  โ†ณ HomePage.java
ย ย ย ย ย ย ย  โ†ณ BasePage.java

XPath Hierarchy and Structure

XPath represents a node structure that mimics the HTML DOM tree. It allows navigation from parent to child, and across sibling elements.

  • โ€ข / โ€“ Selects root element
  • โ€ข // โ€“ Selects from anywhere in the document
  • โ€ข /html/body/div[2]/form/input โ€“ Absolute path
  • โ€ข //div[@class=’container’]//a โ€“ Relative path with attribute
  • โ€ข //ul/li[1] โ€“ Navigates to child elements

XPath Axes (Hierarchy Navigation)

  • โ€ข parent:: โ€“ Selects the parent of the current node
  • โ€ข child:: โ€“ Selects the children
  • โ€ข ancestor:: โ€“ Selects all ancestors (parents, grandparents, etc.)
  • โ€ข descendant:: โ€“ All children, grandchildren, etc.
  • โ€ข following-sibling:: โ€“ Nodes on the same level after current node

OOP Concepts Hierarchy in Java + Selenium

Selenium test frameworks in Java are built on Object-Oriented Principles. Hereโ€™s the conceptual breakdown:

  • โ€ข Class โ€“ Blueprint for objects (e.g., BaseTest, LoginPage)
  • โ€ข Object โ€“ Instance of a class
  • โ€ข Inheritance โ€“ Allows reuse (e.g., TestClass extends BaseClass)
  • โ€ข Polymorphism โ€“ Multiple forms of a method (e.g., overloading login())
  • โ€ข Abstraction โ€“ Hiding implementation (e.g., using interfaces or abstract classes)
  • โ€ข Encapsulation โ€“ Wrapping data (e.g., private variables with getters/setters)

Example: Login Page in OOP + POM

public class LoginPage {
ย  private WebDriver driver;

ย  @FindBy(id = “email”)
ย  private WebElement emailField;

ย  public LoginPage(WebDriver driver) {
ย ย ย  this.driver = driver;
ย ย ย  PageFactory.initElements(driver, this);
ย  }

ย  public void login(String email, String pwd) {
ย ย ย  emailField.sendKeys(email);
ย ย ย  // similar for password and click
ย  }
}

Summary

Understanding these hierarchies helps design scalable automation frameworks. POM separates responsibilities, XPath provides precise navigation in the DOM, and OOP organizes code logically and modularly.

Selenium for Beginners โ€“ Page 17

Introduction to Healenium โ€“ A Self-Healing Test Automation Tool

In modern automation, one of the biggest challenges is maintaining test cases due to changes in the application’s UI. Healenium is an open-source solution that adds self-healing capability to Selenium-based test frameworks. This means when locators break due to changes in the DOM, Healenium attempts to auto-heal the test during runtime.

What is Healenium?

Healenium is a library that integrates with Selenium and automatically fixes broken element locators by using AI and historical context. It was developed to reduce flakiness in automated UI tests and increase test stability without manually updating locators.

Why Do Tests Fail Due to Locators?

  • โ€ข The UI changes but the test script still expects the old structure.
  • โ€ข Element IDs or class names get updated during deployment.
  • โ€ข The position of elements shifts in the DOM tree.
  • โ€ข Developers restructure HTML layouts and containers.

How Healenium Works

Healenium keeps a history of element locators and their context. If the test fails to find an element using the original locator, it uses machine learning to find a similar one based on previous interactions.

Key concepts:

  • โ€ข HL Locator โ€“ A wrapper around Selenium locators that enables healing.
  • โ€ข Healing Engine โ€“ Uses saved history and similarity algorithms to recover broken selectors.
  • โ€ข Dashboard โ€“ Visual tool to inspect healed locators and review healing behavior.

Benefits of Using Healenium

  • โ€ข Reduces test flakiness.
  • โ€ข Saves time spent updating locators after UI changes.
  • โ€ข Improves test reliability during Agile development.
  • โ€ข Helps detect trends in UI instability.

Basic Setup Overview (Java)

To use Healenium with Selenium (Java):
1. Add Healenium and SLF4J dependencies to your Maven `pom.xml`.
2. Replace `WebDriver` with `HealingDriver` in your framework.
3. Add HL locators using `By.cssSelector().hl()` or `By.xpath().hl()`
4. Configure healing service URL if using external dashboard.

Sample Code Snippet

HealingDriver driver = new HealingDriver(new ChromeDriver());
driver.findElement(By.xpath(“//input[@id=’username’]”)).sendKeys(“admin”);

When Not to Use Healenium

โ€ข When your UI is very stable and rarely changes
โ€ข For mission-critical validations where precision is more important than flexibility
โ€ข If your team prefers strict locator tracking and manual updates

Summary

Healenium is a powerful addition to modern Selenium frameworks. It brings self-healing capabilities using AI to keep test automation resilient against DOM changes. By integrating it into your project, especially during rapid UI development, you reduce maintenance time and boost test robustness.

Selenium for Beginners โ€“ Page 18

Advanced Healenium Concepts + Missed Selenium Essentials

This chapter dives deeper into Healeniumโ€™s advanced capabilities, integration tips, and maintenance strategies. It also revisits several lesser-discussed Selenium features to complete your beginner-to-advanced transition.

Advanced Healenium Capabilities

  • โ€ข Healing Engine Tuning โ€“ Customize matching thresholds using healing.properties file.
  • โ€ข Healenium Dashboard โ€“ Visual dashboard (optional) that logs and compares healed vs original locators.
  • โ€ข Healing History โ€“ Tracks past failures and healed decisions to improve predictions.
  • โ€ข Selector Similarity Algorithm โ€“ Uses XPath distance and DOM weight for closest match estimation.
  • โ€ข REST API for Healing โ€“ Allows monitoring and querying healing decisions.

Using Healenium Dashboard

The dashboard helps QA teams visualize healing behaviors over time. You can see metrics like: how often healing occurred, which selectors needed healing most, and performance impact.

Healenium Setup Tips (Advanced)

  • โ€ข Use it only on dynamic elements. Static sections can stick to standard WebDriver.
  • โ€ข Monitor dashboard weekly to update and fix unstable locators manually.
  • โ€ข Combine with reporting tools like Allure or ExtentReports for traceability.
  • โ€ข Customize healing engineโ€™s similarity settings for higher precision or recall.

Missed But Important Selenium Concepts

1. WebDriverWait vs FluentWait

โ€ข WebDriverWait waits until a condition is true with fixed polling intervals.
โ€ข FluentWait allows flexible polling time, ignored exceptions, and timeout conditions.

2. JavaScriptExecutor

โ€ข Execute JavaScript directly on the page when standard WebDriver actions fail.
โ€ข Example: scroll, clicking hidden buttons, retrieving hidden values.

3. DesiredCapabilities (Deprecated) & Options

โ€ข Older Selenium versions used DesiredCapabilities.
โ€ข Now use ChromeOptions, FirefoxOptions to set browser preferences like headless, user-agent, etc.

4. Taking Screenshots

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

5. Mobile Emulation in Selenium

ChromeDriver allows simulating mobile devices using ChromeOptions and device metrics.

6. WebDriverManager

โ€ข A tool that automatically manages browser driver binaries (no need to download chromedriver manually).

Integrating Healenium with Reporting Tools

Use listeners or wrappers to log healing events in your test reports (Allure, TestNG reports, etc.). You can also hook into exceptions and decorate logs with โ€˜healedโ€™ labels to flag unstable areas.

Summary

Healenium becomes more powerful when used selectively and monitored properly. Combined with core Selenium strategies like custom waits, JavaScriptExecutor, and visual dashboards, you can create stable, future-proof test frameworks. Learning these advanced details completes your Selenium beginner foundation.

Selenium for Beginners โ€“ Page 19

Medium to Advanced Selenium Concepts for Test Automation Engineers

As you move beyond beginner topics, itโ€™s essential to understand practical strategies and integrations that support robust and maintainable Selenium automation frameworks. This chapter outlines medium to advanced topics useful in real-world automation work.

1. Selenium Grid 4 โ€“ Parallel and Remote Execution

Selenium Grid allows you to run tests in parallel across multiple machines or browsers. With Selenium Grid 4, the architecture supports distributed mode (Hub, Node, Router, Distributor, etc.) via Docker or standalone.

Key Benefits:

  • โ€ข Reduces execution time via parallel tests
  • โ€ข Supports cross-browser and cross-platform testing
  • โ€ข Easily scalable in CI pipelines

2. Docker with Selenium Grid

Using Docker containers, you can spin up isolated browser environments quickly.
For example, use the official Selenium Docker images to launch Chrome/Firefox nodes without manual installation.

Sample command:

docker run -d -p 4444:4444 selenium/standalone-chrome

3. Running Selenium Tests via Jenkins

Jenkins enables test automation execution after code changes. Create Jenkins jobs that:
โ€ข Pull test scripts from GitHub
โ€ข Run `mvn test` to execute tests
โ€ข Publish HTML reports

4. Reporting Integration โ€“ Allure

Allure is a beautiful test report library that supports TestNG, JUnit, and BDD. It can attach screenshots, logs, and step details.

Steps:

  • โ€ข Add Allure dependency to Maven pom.xml
  • โ€ข Use annotations like @Step or @Attachment
  • โ€ข Generate report using allure:report goal

5. Creating Custom Waits

Beyond WebDriverWait and FluentWait, you can write reusable wait methods using ExpectedConditions or lambda expressions for repeated use.

6. Sync API and UI Tests

Sometimes, validating APIs alongside UI flows helps catch backend issues faster. Use RestAssured or HTTPClient to send API requests before/after UI validation.

7. Reading JSON/YAML for Test Data

Instead of hardcoded data or Excel, modern frameworks use lightweight formats like JSON or YAML.
You can parse them with libraries like Jackson or SnakeYAML.

8. Exception Recovery Techniques

Add recovery logic inside `catch` blocks:

  • โ€ข Retry the failed step
  • โ€ข Take a screenshot and log it
  • โ€ข Trigger alerts or skip further steps

Summary

By combining Selenium with Docker, Grid, Jenkins, and API validations, you build a real-world-ready test framework. Advanced test data handling, customized waits, and better exception handling further improve reliability and speed.

ย 

Scroll to Top