Building a Selenium Framework from Scratch: Step-by-Step Guide

Building a Selenium Framework from Scratch: Step-by-Step Guide

Table of Contents

Introduction

In today’s fast-paced software development landscape, test automation has become essential. Among the many automation tools available, Selenium Framework stands out as the most widely adopted open-source solution for automating web applications. However, simply writing scripts isn’t enough you need a robust Selenium framework to ensure maintainability, scalability, and reusability.

This provides a step-by-step guide to building a Selenium framework from scratch using Java, TestNG, Maven, and other supporting tools. Whether you’re a beginner pursuing a Selenium Certification or a professional QA engineer, this guide will help you lay the groundwork for a solid test automation strategy.

What Is a Selenium Framework?

A Selenium Framework is a structured and reusable automation testing architecture built using the Selenium tool. It serves as the foundation for writing and managing test scripts efficiently by integrating various components like Selenium WebDriver, TestNG or JUnit, Maven, reporting tools, and utility libraries. Rather than writing isolated test cases, a framework helps organize code in a modular, maintainable, and scalable way.

At its core, a Selenium framework separates the test logic from UI interactions, often using the Page Object Model (POM) or other design patterns. This separation enhances code reusability and reduces maintenance time when application elements change. Frameworks also support features like centralized configurations, logging, parallel execution, data-driven testing, and integration with CI/CD pipelines.

There are several types of Selenium frameworks, including modular, data-driven, keyword-driven, hybrid, and behavior-driven development (BDD) frameworks using tools like Cucumber. Each serves different testing needs and levels of complexity.

Building a Selenium Framework from Scratch: Step-by-Step Guide

Mastering a Selenium framework is often a key requirement in job roles related to test automation. Therefore, those pursuing a Selenium Training or a career in QA automation benefit greatly from learning how to build and maintain these frameworks effectively. It’s an essential skill for delivering reliable, fast, and maintainable automated test solutions.

  • Code reusability
  • Better test organization
  • Easy maintenance
  • Scalability
  • Integration with CI/CD pipelines

Why Build a Custom Selenium Framework?

Building a custom Selenium framework offers flexibility, control, and long-term efficiency in test automation. While out-of-the-box solutions and record-playback tools can handle basic tasks, they often fall short in handling complex test scenarios, scalability, and integration needs. A custom framework allows QA teams to tailor the architecture to match the project’s requirements and coding standards.

One of the biggest advantages of a custom framework is modularization. By using design patterns like the Page Object Model (POM), test logic and UI elements are separated, making the codebase easier to maintain. As the application evolves, changes can be made quickly without rewriting entire test cases. Custom frameworks also support data-driven testing, enabling testers to run the same tests with multiple sets of input data from Excel, CSV, or databases.

Other benefits include integration with reporting tools, continuous integration pipelines (e.g., Jenkins), version control systems (e.g., Git), and containerization platforms like Docker. Custom frameworks also allow better parallel execution, improving test speed and efficiency.

For professionals working toward a Selenium certification, the ability to build a custom Selenium framework showcases practical expertise and problem-solving skills both of which are highly valued in automation testing careers.

Benefits:

  • Modular architecture
  • Easy bug identification and resolution
  • Seamless reporting
  • Parallel execution support
  • Integration with tools like Jenkins, Git, and Docker

Prerequisites Before You Start

Before building your framework, ensure you have the following:

  • Java Development Kit (JDK) installed
  • IDE: IntelliJ IDEA, Eclipse, or similar
  • Maven: For dependency management
  • TestNG: For test execution management
  • Selenium WebDriver
  • Git: Version control system
  • Knowledge of OOP concepts

Step 1: Set Up Your Project Environment

Create a Maven Project

Maven simplifies project management and dependency handling. You can generate a Maven project via the IDE or command line.

Sample pom.xml Dependencies:

xmlCopy<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.19.1</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.9.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>5.8.0</version>
    </dependency>
</dependencies>

Step 2: Define Your Folder Structure

Maintain a clean directory structure for better manageability.

cssCopysrc
├── main
│   ├── java
│   │   ├── base
│   │   ├── pages
│   │   ├── utils
├── test
│   ├── java
│   │   ├── tests
└── resources
    ├── config.properties
    ├── testdata.xlsx

Folder Description:

  • base: Contains BaseTest and BasePage classes
  • pages: Contains Page Object Model classes
  • utils: Utility functions (e.g., Excel reader, wait conditions)
  • tests: TestNG test scripts
  • resources: Configuration and data files

Step 3: Create a Base Class for Initialization

Your BaseTest class will handle setup and teardown using @BeforeMethod and @AfterMethod.

javaCopypublic class BaseTest {
    protected WebDriver driver;

    @BeforeMethod
    public void setUp() {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        driver.get("https://example.com");
        driver.manage().window().maximize();
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Step 4: Implement Page Object Model (POM)

POM separates the UI and test logic, increasing maintainability.

LoginPage.java

javaCopypublic class LoginPage {
    private WebDriver driver;

    @FindBy(id = "username")
    WebElement username;

    @FindBy(id = "password")
    WebElement password;

    @FindBy(id = "loginBtn")
    WebElement loginBtn;

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

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

Step 5: Create Your Test Classes Using TestNG

LoginTest.java

javaCopypublic class LoginTest extends BaseTest {
    @Test
    public void verifyLogin() {
        LoginPage login = new LoginPage(driver);
        login.login("admin", "admin123");
        Assert.assertEquals(driver.getTitle(), "Dashboard");
    }
}

Step 6: Externalize Configurations

Create a config.properties file in resources:

propertiesCopybaseUrl=https://example.com
browser=chrome
username=admin
password=admin123

Create a utility class to load configurations:

javaCopypublic class ConfigLoader {
    public static Properties loadConfig() throws IOException {
        FileInputStream file = new FileInputStream("src/test/resources/config.properties");
        Properties prop = new Properties();
        prop.load(file);
        return prop;
    }
}

Step 7: Add Utility Functions

WaitUtils.java

javaCopypublic class WaitUtils {
    public static void waitForVisibility(WebDriver driver, WebElement element, int timeout) {
        new WebDriverWait(driver, Duration.ofSeconds(timeout))
            .until(ExpectedConditions.visibilityOf(element));
    }
}

Step 8: Data-Driven Testing with Excel

Use Apache POI to read Excel test data.

ExcelReader.java

javaCopypublic class ExcelReader {
    public String getCellData(String sheetName, int row, int col) {
        try {
            FileInputStream fis = new FileInputStream("src/test/resources/testdata.xlsx");
            Workbook wb = WorkbookFactory.create(fis);
            return wb.getSheet(sheetName).getRow(row).getCell(col).toString();
        } catch (Exception e) {
            return null;
        }
    }
}

Step 9: Generate Reports Using TestNG

TestNG automatically generates HTML reports post-execution.

To customize:

  • Use ExtentReports or Allure for detailed reports.
  • Add listeners for advanced test tracking.

Step 10: Parallel Execution with TestNG XML

testng.xml

xmlCopy<suite name="SeleniumSuite" parallel="tests" thread-count="2">
    <test name="LoginTest">
        <classes>
            <class name="tests.LoginTest"/>
        </classes>
    </test>
</suite>

Step 11: Integrate with Jenkins

To automate test runs:

  1. Install Jenkins.
  2. Create a new job.
  3. Pull the project from Git.
  4. Add Maven command: mvn clean test
  5. Schedule builds and view reports from Jenkins dashboard.

Step 12: Dockerize Your Selenium Grid

Run Selenium Grid via Docker:

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

Update your test setup to use RemoteWebDriver pointing to http://localhost:4444/wd/hub.

Building a Selenium Framework from Scratch: Step-by-Step Guide

Best Practices

  • Use meaningful test method names.
  • Keep locators centralized in page classes.
  • Implement logging (e.g., Log4j).
  • Use assertions wisely.
  • Keep tests independent.

Conclusion

Building a Selenium framework from scratch offers unparalleled control and customization for your test automation needs. With Java, TestNG, Maven, and best practices in place, you can build a powerful, reusable, and scalable automation suite that integrates seamlessly into any CI/CD pipeline. Many Selenium Online Courses now include hands-on modules to help learners gain real-world experience in building such frameworks from the ground up.

Whether you are building your first test suite or upgrading an existing one, following this guide ensures a clean, modular, and future-proof test architecture.

Key Takeaways

Integrate CI tools like Jenkins and Docker for efficiency.

A custom Selenium framework improves test maintenance and scalability.

Design a clean architecture using Java, Maven, and TestNG.

Apply POM and utilities for reusability.

Externalize configs and use data-driven techniques.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Enroll Free demo class
Enroll IT Courses

Need a Free Demo Class?
Join H2K Infosys IT Online Training
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.

Join Free Demo Class

Let's have a chat