Building Your First Selenium Framework: A Step-By-Step Tutorial

Samiksha KuteSamiksha Kute
9 min read

Welcome to the world of Selenium Framework development! In this blog, we’ll walk through a comprehensive guide to creating an end-to-end Selenium Framework for UI automation testing. Whether you’re new to automation or looking to level up your skills, this guide will break down complex concepts into simple, easy-to-understand steps. We’ll cover everything from setting up a Maven project to automating an e-commerce application and implementing industry-standard practices.

Prerequisites: Getting Ready for the Selenium Framework

Before we start building our Selenium Framework, it’s important to have a solid foundation in the following areas:

  1. Selenium Basics: Ensure you’re comfortable with core Selenium concepts like locators, WebDriver, and browser interactions.

  2. TestNG: Since TestNG will be heavily used in this framework, make sure you understand its annotations, test grouping, and parameterization.

  3. Java Concepts: Familiarity with Java streams, explicit/implicit waits, and the Actions class is crucial, as we’ll use these extensively.

  4. Prior Sections: The framework builds on topics like automation basics, Java streams, waits, and TestNG, so review these if needed.

If you feel unsure about any of these, the instructor recommends brushing up with Selenium interview questions to solidify your knowledge. You can reach out to the instructor for a list of high-level Selenium API questions commonly asked in interviews.

What’s the Goal of This Framework?

The goal is to create a robust, enterprise-level Selenium Framework that automates an end-to-end flow for an e-commerce application. Here’s what we’ll achieve:

  • End-to-End Automation: Automate a complete user journey, from logging into an e-commerce site to placing an order.

  • Industry Standards: Implement best practices like the Page Object Model (POM), design patterns, and data-driven testing.

  • TestNG Integration: Use TestNG for test execution, grouping, parameterization, and reporting.

  • Advanced Features: Incorporate features like screenshot capture on test failure, logging, extent reports, parallel execution, and automatic rerun of failed tests.

  • CI/CD Integration: Learn how to integrate the framework with Jenkins for automated test execution.

  • Cucumber Wrapper: Add a Cucumber layer with feature files, step definitions, and tags for behavior-driven development (BDD).

Let’s get started!

Step 1: Setting Up a Maven Project

What is Maven?

Maven is a build automation tool that simplifies project setup by providing a standard structure and managing dependencies (like Selenium and TestNG libraries). It’s widely used in automation projects because it automatically downloads required libraries (JARs) from the Maven Repository.

Creating a Maven Project

  1. Open Your IDE: In Eclipse, right-click in the Project Explorer, select New > Project, and choose Maven Project.

  2. Select Archetype: An archetype is a template for your project structure. Filter for maven-archetype-quickstart with the group ID org.apache.maven.archetypes. This is the default template for a simple Java project suitable for automation.

  3. Configure Project Details:

    • Group ID: This represents the organization or company (e.g., seleniumhq). Think of it as the parent hierarchy.

    • Artifact ID: This is your project name (e.g., SeleniumFrameworkDesign).

    • Package: Set it to match the group ID (e.g., seleniumhq) for consistency.

  4. Finish Setup: Click Finish, and Maven will create a project with a standard folder structure, including src/main/java (for reusable utilities) and src/test/java (for test cases). A pom.xml file is generated, which is the heart of a Maven project.

Understanding the pom.xml File

The pom.xml (Project Object Model) file contains project details and dependencies. It includes:

  • Group ID and Artifact ID: These uniquely identify your project.

  • Dependencies: Libraries your project needs, like Selenium and TestNG.

Adding Dependencies

  1. Selenium Dependency:

    • Visit mvnrepository.com and search for “Selenium”.

    • Select the latest version of selenium-java (e.g., 4.3.0).

    • Copy the dependency code and paste it into the <dependencies> section of pom.xml.

    • Save the file, and Maven will automatically download the Selenium JARs. You’ll see them in the Maven Dependencies folder in your project.

  2. TestNG Dependency:

    • Search for “TestNG” on mvnrepository.com.

    • Choose the appropriate version based on your Java version:

      • For Java 11 or higher, select the latest version (e.g., 7.x).

      • For Java 8, select the latest version compatible with Java 8 (e.g., 6.14.3).

    • Copy the dependency code, paste it into pom.xml, and save. TestNG JARs will be downloaded.

  3. WebDriverManager Dependency:

    • Search for “WebDriverManager” on mvnrepository.com.

    • Add the latest version to pom.xml. This library simplifies browser driver management by automatically downloading the correct ChromeDriver version.

After adding these dependencies, your project is ready to use Selenium, TestNG, and WebDriverManager.

Step 2: Creating a Standalone End-to-End Test

Before building the framework, we need a working Selenium test to automate an e-commerce application. This test will serve as the foundation for our framework. We’ll use the e-commerce site at rahulshettyacademy.com/client.

Understanding the E-Commerce Application

The application allows users to:

  1. Log in with an email and password.

  2. Browse products and add items (e.g., “ZARA COAT 3”) to the cart.

  3. Verify the product in the cart.

  4. Check out by filling in details and selecting a country.

  5. Confirm the order and verify the order ID on the confirmation page.

  6. View and delete orders from the order history page.

Writing the Standalone Test

Let’s create a test class called StandAloneTest in the src/test/java package. Here’s how we’ll automate the end-to-end flow:

  1. Set Up WebDriver:

    • Use WebDriverManager to set up ChromeDriver: WebDriverManager.chromedriver().setup().

    • Create a ChromeDriver instance: WebDriver driver = new ChromeDriver().

    • Maximize the browser: driver.manage().window().maximize().

    • Set an implicit wait of 10 seconds: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)).

    • Navigate to the e-commerce site: driver.get("https://rahulshettyacademy.com/client").

  2. Log In:

    • Locate the email field using By.id("userEmail") and enter your email.

    • Locate the password field using By.id("userPassword") and enter your password.

    • Click the login button using By.id("login").

  3. Add Product to Cart:

    • Identify all products on the page using a CSS selector: .mb-3 (this class is common to all product cards).

    • Store the products in a list: List<WebElement> products = driver.findElements(By.cssSelector(".mb-3")).

    • Use Java Streams to find the product “ZARA COAT 3”:

      java

        WebElement prod = products.stream()
            .filter(product -> product.findElement(By.cssSelector("b")).getText().equals("ZARA COAT 3"))
            .findFirst()
            .orElse(null);
      
      • This code iterates through the product list, checks if the product title (inside a <b> tag) matches “ZARA COAT 3”, and returns the matching product.
    • Click the “Add to Cart” button for the selected product using a CSS selector: .card-body button:last-of-type.

  4. Verify Product Addition:

    • Wait for the toast message confirming the product was added using an explicit wait:

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#toast-container")));
      
    • Wait for the loading icon to disappear:

        wait.until(ExpectedConditions.invisibilityOf(driver.findElement(By.cssSelector(".ng-animating"))));
      
  5. Go to Cart:

    • Click the cart button using By.cssSelector("[routerlink*='cart']").
  6. Verify Product in Cart:

    • Get all products in the cart using a CSS selector: .cartSection h3.

    • Use Java Streams to check if “ZARA COAT 3” is present:

        List<WebElement> cartProducts = driver.findElements(By.cssSelector(".cartSection h3"));
        boolean match = cartProducts.stream()
            .anyMatch(cartProduct -> cartProduct.getText().equalsIgnoreCase("ZARA COAT 3"));
        Assert.assertTrue(match);
      
  7. Checkout:

    • Click the checkout button: By.cssSelector(".totalRow button").

    • Enter the country name (e.g., “India”) using the Actions class:

        Actions a = new Actions(driver);
        a.sendKeys(driver.findElement(By.cssSelector("[placeholder='Select Country']")), "India").build().perform();
      
    • Wait for the country dropdown to appear: wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".ta-results"))).

    • Select the second option (India) using an XPath: By.xpath("(//button[contains(@class, 'ta-item')])[2]").

    • Click the “Place Order” button: By.cssSelector(".action__submit").

  8. Verify Order Confirmation:

    • Capture the confirmation message: String confirmMessage = driver.findElement(By.cssSelector(".hero-primary")).getText().

    • Assert the message matches “THANK YOU FOR THE ORDER” (case-insensitive):

        Assert.assertTrue(confirmMessage.equalsIgnoreCase("THANK YOU FOR THE ORDER"));
      
  9. Close the Browser:

    • driver.quit().

Running the Test

Run the test to ensure it logs in, adds “ZARA COAT 3” to the cart, verifies it, checks out, and confirms the order. The test should pass without errors, confirming the end-to-end flow works.

Step 3: Converting the Standalone Test into a Framework

Now that we have a working standalone test, it’s time to transform it into a robust framework using industry-standard practices. Here’s what we’ll do:

  1. Page Object Model (POM):

    • Organize the test by creating separate classes for each page (e.g., LoginPage, ProductPage, CartPage, CheckoutPage).

    • Encapsulate locators and actions (e.g., clickLogin(), addToCart()) in these classes to improve maintainability.

  2. Design Patterns:

    • Use patterns like Factory or Singleton to manage WebDriver instances and page objects efficiently.
  3. Base Test Class:

    • Create a BaseTest class to handle common setup (e.g., initializing WebDriver, setting waits) and teardown (e.g., closing the browser).
  4. Configuration and Global Properties:

    • Set up a configuration file (e.g., config.properties) to store URLs, credentials, and other settings.

    • Use this file to make the framework adaptable to different environments.

  5. Test Strategy:

    • Define a strategy for test execution, including which tests to run and in what order.
  6. TestNG Features:

    • Grouping: Group tests (e.g., smoke, regression) for selective execution.

    • Parameterization: Pass test data (e.g., email, password) via TestNG XML or data providers.

    • Data-Driven Testing: Use Excel, CSV, or JSON files to drive tests with multiple data sets.

    • Listeners: Capture screenshots on test failure using TestNG listeners.

    • Parallel Execution: Run tests in parallel to reduce execution time.

    • Rerun Failed Tests: Automatically rerun failed tests using TestNG’s retry analyzer.

    • Extent Reports: Generate detailed HTML reports for test results.

  7. Maven Integration:

    • Use Maven commands to control test execution (e.g., mvn test).

    • Pass runtime variables (e.g., browser type) via Maven for flexibility.

  8. Jenkins Integration:

    • Integrate the framework with Jenkins for continuous integration.

    • Parameterize Jenkins builds and schedule nightly runs for automated testing.

  9. Cucumber Wrapper:

    • Add Cucumber for BDD by creating feature files, step definitions, and Cucumber TestNG runners.

    • Use Cucumber tags to organize and run specific scenarios.

    • Implement data-driven testing within Cucumber.

Step 4: Building the Framework

Over the next few hours, the instructor will guide you through implementing these features. Here’s a high-level overview of the process:

  1. Refactor the Test:

    • Move locators and actions from StandAloneTest to page object classes.

    • Update the test to call methods from these classes (e.g., loginPage.login(email, password)).

  2. Set Up Framework Components:

    • Create a BaseTest class to initialize WebDriver and load configurations.

    • Implement utility classes for logging, screenshot capture, and reporting.

  3. Add TestNG Features:

    • Configure TestNG XML for test suites, groups, and parameters.

    • Add listeners for failure handling and reporting.

  4. Integrate with Maven and Jenkins:

    • Use Maven to manage dependencies and execute tests.

    • Set up Jenkins to trigger tests automatically and pass parameters.

  5. Incorporate Cucumber:

    • Write feature files describing the e-commerce flow in Gherkin syntax.

    • Create step definitions to map Gherkin steps to Selenium code.

    • Run Cucumber tests using TestNG runners.

By the end, you’ll have a robust framework that follows industry standards.

Conclusion

Building a Selenium Framework is a rewarding process that combines Selenium, TestNG, Maven, Jenkins, and Cucumber into a powerful automation solution. By following this guide, you’ve learned how to:

  1. Set up a Maven project and add dependencies.

  2. Create a standalone end-to-end test for an e-commerce application.

  3. Transform the test into a framework using POM, TestNG, and other best practices.

  4. Integrate with CI/CD tools and add a Cucumber layer.

This framework will not only enhance your automation skills but also make you stand out in interviews. Keep practicing, stay curious, and happy automating!

0
Subscribe to my newsletter

Read articles from Samiksha Kute directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Samiksha Kute
Samiksha Kute

Passionate Learner!