Building a Selenium Automation Framework: A Step-by-Step Guide (Part 1)

Samiksha KuteSamiksha Kute
7 min read

Welcome to the exciting world of Selenium automation! If you’re new to automation testing or looking to level up your skills, this blog is for you. In this blog, we’ll walk through the process of creating an end-to-end Selenium automation framework, step by step, in a way that’s easy to understand. This is Part 1 of the series, where we’ll cover the basics of setting up a Maven project, creating a standalone Selenium test, and automating an e-commerce website. Let’s dive in!

Prerequisites: Brush Up on Selenium and TestNG

Before we start, make sure you’re comfortable with the core concepts of Selenium and TestNG. These are the building blocks for what we’re about to do. You should be familiar with:

  • Selenium concepts: Things like Java streams, explicit and implicit waits, and the Actions class.

  • TestNG: A testing framework that we’ll use heavily to structure and run our tests.

If you need a refresher, check out my previous blogs in the Selenium Series.

What’s the Goal?

In this series, we’re going to build a robust, enterprise-level Selenium automation framework. Here’s what we’ll cover:

  • Creating a Maven-based framework: We’ll set up a project structure using Maven, a tool that simplifies dependency management.

  • Automating an end-to-end flow: We’ll work with a brand-new e-commerce application to simulate a real-world scenario, from logging in to placing an order.

  • Implementing advanced concepts: This includes the Page Object Model (POM), design patterns, configuration setups, global properties, and test strategies.

  • TestNG integration: We’ll use TestNG for grouping, parameterization, data-driven testing, capturing screenshots on test failures, generating logs, creating Extent Reports, running tests in parallel, and rerunning failed tests.

  • Maven and Jenkins integration: We’ll learn how to control test execution with Maven commands and integrate the framework with Jenkins for automated, scheduled test runs.

  • Cucumber wrapper: We’ll add Cucumber to the framework, including feature files, step definitions, tags, and data-driven testing.

  • Interview preparation: At the end, we’ll cover common Selenium framework-related interview questions and tie them back to the framework we’ve built.

This journey will take some time, so stay patient and motivated! By the end, you’ll have a solid understanding of how to build a professional-grade automation framework.

Step 1: Setting Up a Maven Project

Let’s start by creating a new Maven project, which will serve as the foundation for our framework. Maven is a tool that helps manage dependencies (like Selenium and TestNG libraries) and organizes your project structure.

How to Create a Maven Project

  1. Open your IDE (e.g., Eclipse) and right-click to create a new project.

  2. Select Maven Project and click “Next.”

  3. Choose the default workspace location and move to the next step.

  4. You’ll see a list of archetypes (predefined project templates). For automation, we’ll use the maven-archetype-quickstart template. Search for it using the filter, and ensure the Group ID is org.apache.maven.archetypes.

  5. Click “Next” and provide the following details:

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

    • Group ID: Think of this as the parent organization or company name, e.g., com.selenium. It represents the hierarchy under which your project sits.

    • Package: This defines the package structure for your code. For simplicity, keep it the same as the Group ID (selenium-demo).

  6. Click “Finish” to create the project.

What Happens Next?

Maven creates a project with a standard structure:

  • src/main/java: For reusable utilities and page object files (we’ll cover these later).

  • src/test/java: For writing test cases.

  • pom.xml: The heart of a Maven project, where dependencies are defined.

The pom.xml file will include the Group ID, Artifact ID, and version details. If you want to share your project with others, you can publish it to the Maven Repository using these details.

Adding Dependencies

To use Selenium and TestNG, we need to add their dependencies to the pom.xml file. Here’s how:

Selenium Dependency:

  • Go to mvnrepository.com and search for “Selenium.”

  • Select the latest version of Selenium Java (e.g., 4.3.0).

  • Copy the dependency code (four lines) and paste it into the <dependencies> section of your pom.xml.

  • Remove the default JUnit dependency, as we’ll use TestNG instead.

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

TestNG Dependency:

  • Search for “TestNG” on mvnrepository.com.

  • Choose the appropriate version based on your Java version:

    • For Java 11 or higher, select a version starting from 7.x.

    • For Java 8, select the latest version of 6.x (e.g., 6.14.3).

  • Copy the dependency code and add it to pom.xml.

  • Save the file, and TestNG JARs will be downloaded.

Now your project is ready with all the necessary libraries!

Step 2: Understanding the E-Commerce Application

Before we write any code, let’s explore the e-commerce application we’ll automate. The website is accessible at Example Website. Here’s the flow we’ll automate:

  • Create an Account: Register with a unique email and password. Remember these credentials, as you’ll need them for login.

  • Log In: Use your credentials to access the dashboard.

  • Select a Product: Choose a product (e.g., “ZARA COAT 3”) and add it to the cart.

  • Validate Cart Addition: Verify that a “Product Added to Cart” message appears.

  • Go to Cart: Check if the selected product appears in the cart.

  • Checkout: Fill in payment details, select a country, and place the order.

  • Verify Order Confirmation: Ensure the “Thank you for the order” message appears and grab the order ID.

  • Check Order History: Go to the orders tab to verify that the order appears and matches the order ID.

  • View and Delete Orders: View order details and delete the order if needed.

This end-to-end flow mimics a real-world shopping scenario, making it a great example for automation.

Step 3: Writing a Standalone Selenium Test

Now, let’s create a standalone Selenium test to automate this flow. This test will serve as the foundation for our framework. We’ll write it in a class called StandaloneTest under src/test/java.

Setting Up the Test

  • Delete Default Files: Remove the default App.java and AppTest.java files created by Maven, as we don’t need them.

  • Create a New Class: Right-click on the package under src/test/java, create a new class named StandaloneTest, and start coding.

Initialize ChromeDriver:

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://rahulshettyacademy.com/client");

Log In:

driver.findElement(By.id("userEmail")).sendKeys("your_email@example.com");
driver.findElement(By.id("userPassword")).sendKeys("your_password");
driver.findElement(By.id("login")).click();

Selecting a Product and Adding to Cart

Get the Product List:

List<WebElement> products = driver.findElements(By.cssSelector(".mb-3"));

Find the Desired Product:

WebElement prod = products.stream()
    .filter(product -> product.findElement(By.cssSelector("b")).getText().equals("ZARA COAT 3"))
    .findFirst()
    .orElse(null);

Click Add to Cart:

prod.findElement(By.cssSelector(".card-body button:last-of-type")).click();

Handling Synchronization

Wait for Toast Message:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#toast-container")));

Wait for Loading Icon to Disappear:

wait.until(ExpectedConditions.invisibilityOf(driver.findElement(By.cssSelector(".ng-animating"))));

Navigating to the Cart

driver.findElement(By.cssSelector("[routerlink*='cart']")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".cartSection h3")));

Validating the Cart

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

Checking Out

driver.findElement(By.cssSelector(".totalRow button")).click();

Handling the Country Dropdown

Actions a = new Actions(driver);
a.sendKeys(driver.findElement(By.cssSelector("[placeholder='Select Country']")), "India").build().perform();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".ta-results")));
driver.findElement(By.xpath("(//button[contains(@class, 'ta-item')])[2]")).click();

Placing the Order

driver.findElement(By.cssSelector(".action__submit")).click();

Verifying the Confirmation Page

String confirmMessage = driver.findElement(By.cssSelector(".hero-primary")).getText();
Assert.assertTrue(confirmMessage.equalsIgnoreCase("Thank you for the order"));

Closing the Browser

driver.quit();

Running the Test

Run the test to ensure it works. It should:

  • Log in.

  • Add “ZARA COAT 3” to the cart.

  • Verify the toast message and loading icon.

  • Navigate to the cart and validate the product.

  • Complete the checkout process.

  • Verify the order confirmation.

If everything works, you’ll see no failures in the console!

Check out the complete source code repository below for reference:

What’s Next?

We’ve created a standalone Selenium test that automates an end-to-end e-commerce flow. In Part 2, we’ll refactor this test into a professional framework using concepts like the Page Object Model, data-driven testing, and TestNG features. Stay tuned for more advanced topics like parallel execution, Extent Reports, and Jenkins integration.

This is just the beginning of building a robust automation framework. Stay patient, keep practicing, and you’ll master Selenium in no time! See you in Part 2!

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!