Selenium Automation for E-commerce Websites


E-commerce websites are complex platforms where functionality, user experience, and performance are critical for success. Testing such applications manually can be time-consuming and prone to human error. Selenium, an open-source automation testing tool, is ideal for automating e-commerce applications due to its flexibility, extensive browser support, and integration capabilities. In this blog, we’ll explore how to approach Selenium automation for e-commerce websites with examples, best practices, and common scenarios.


Why Automate E-commerce Testing?

E-commerce platforms include a wide array of features such as product catalogs, shopping carts, payment gateways, and user accounts. Automation ensures:

  • Improved Efficiency: Automation can execute repetitive tasks quickly.

  • Enhanced Accuracy: Reduces human errors in test execution.

  • Scalability: Handles increasing functionality as the website grows.

  • Continuous Feedback: Ensures that new code changes do not break existing features.


Key Challenges in E-commerce Testing

  1. Dynamic Content: Frequent updates to product listings, prices, and offers.

  2. Third-party Integrations: Payment gateways, shipping APIs, and analytics tools.

  3. Responsive Design: Compatibility across multiple devices and browsers.

  4. Concurrency: Handling high user traffic during sales or events.


1. What should you know before automating this assignment?

You should know the following topics before starting this project assignment:

2. Which functionalities will we automate in this project assignment?

We will learn to automate multiple test scenarios of an e-commerce website in this project, like:
  • Learn to automate User Registration and Login using Selenium commands
  • Learn to automate clicking the slide-over menus with the Mouse hover command
  • Learn to automate scroll action using the Mouse Events of the Actions class
  • Learn to automate the Search Product
  • Learn to automate the Add to Cart Page
  • At last, we'll learn to automate the end-to-end functionality of Buy Product.   
  • And we'll automate some other website filters

3. Test Cases for the E-Commerce Website

Let's create a Test Plan for the functionalities that we are going to automate. You can create positive and negative test cases around the following scenarios. We will be using this dummy Online shopping website for this Project Assignment - http://automationpractice.com/index.php. This website works exactly similar to any real e-commerce website like Amazon or Flipkart.

3.1 Testing Registration and Login of the Online Shopping Website

  • Can a guest purchase a product as a guest user?
  • Can a guest register on the website easily?
  • Once registered,  can a user able to log in successfully?
  • Can a registered user able to view all the products listed on the website?
  • Are the user sessions being maintained for the intended time period?
  • Is the user’s session timing out and expiring after a defined time?
  • Is the registered user able to view and modify their user account information?
  • Is the registered user not able to access the user account after logging out?

3.2 Testing Search Feature of the Online Shopping Website

  • Does the website have multiple filters to search products like price range, category, brands, etc.?
  • Are relevant Products displaying after applying single or multiple search filters?
  • Is there an option to display a fixed number of products on the search page?
  • Is there any sort of option available on the search page, and is that working properly?

3.3 Testing the Product Details Page of the Online Shopping Website

  • Is the page displaying all the product information on that page?
  • Can a user select different sizes, colors, and quantities of the product?
  • Is the page displaying any offers if applicable to the product?
  • Is the page displaying the stock information correctly?
  • Is the product getting added cart after doing so?

3.4 Testing the Shopping Cart of the e-commerce website

  • Is the correct price getting displayed in the shopping cart for the selected product/s?
  • Is there an option to apply coupon codes?
  • Can a user increase or decrease the quantity of a product in the shopping cart?
  • Can a user remove the product from the shopping cart?

3.5 Testing the Checkout Flow and Order Confirmation of the Online Shopping Website

  • Is the user able to enter shipping and billing information, or is it auto-filled if the user has already saved it?
  • Are all the supported payment methods working?
  • Is the user's sensitive information handled securely, like credit/debit card info, address, bank details, etc?
  • Does the user receive an email or sms on order confirmation?
  • Can the user track the order?

Common E-commerce Test Scenarios with Selenium

1. User Registration and Login

This section is focused on covering all the scenarios for User Registration for an e-commerce website. In this assignment, you will learn the different Selenium commands that are used to handle the web form. A web form is generally a collection of web elements like text boxes, radio buttons, selection boxes, etc. And in web testing, we mostly face web forms, and 90% of testing revolves around web forms. We are going to cover both positive and negative scenarios for User Registration.

Positive Scenario

1. Test Case - Automate the User Registration process

Steps to Automate:
2. Click on the sign-in link.
3. Enter your email address in the 'Create an Account' section.
4. Click on the Create an Account button.
5. Enter your Personal Information, Address, and Contact info.
6. Click on the Register button.
7. Validate that the user is created.

Selenium code for User Registration

This code is contributed by Uday. We have provided the code for only positive scenarios; you should try automating negative scenarios yourself.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import io.github.bonigarcia.wdm.WebDriverManager;

public class EcomSignUp {

 public static void main(String[] args) {
 
  WebDriverManager.chromedriver().setup();
  WebDriver driver=new ChromeDriver();
  String URL="http://automationpractice.com/index.php";

  driver.get(URL);
  driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
  driver.manage().window().maximize();
  
  //Click on Sign in
  driver.findElement(By.linkText("Sign in")).click();
  
  //Enter email address
  driver.findElement(By.cssSelector("[name='email_create']")).sendKeys("test1249@test.com");
  
  //Click on "Create an account"
  driver.findElement(By.xpath("//button[@name=\"SubmitCreate\"]")).click();
  
  //Select Title
  driver.findElement(By.xpath("//input[@id=\"id_gender1\"]")).click();
  driver.findElement(By.name("customer_firstname")).sendKeys("Test User");
  driver.findElement(By.name("customer_lastname")).sendKeys("Vsoft");
  driver.findElement(By.id("passwd")).sendKeys("PKR@PKR");
  
  // Enter your address
  driver.findElement(By.id("firstname")).sendKeys("Test User");
  driver.findElement(By.id("lastname")).sendKeys("Vsoft");
  driver.findElement(By.id("company")).sendKeys("Vsoft");
  driver.findElement(By.id("address1")).sendKeys("Test 81/1,2nd cross");
  driver.findElement(By.id("city")).sendKeys("XYZ");
  
  // Select State
  WebElement statedropdown=driver.findElement(By.name("id_state"));
  Select oSelect=new Select(statedropdown);
  oSelect.selectByValue("4");

  driver.findElement(By.name("postcode")).sendKeys("51838");
  
  // Select Country
  WebElement countrydropDown=driver.findElement(By.name("id_country"));
  Select oSelectC=new Select(countrydropDown);
  oSelectC.selectByVisibleText("United States");
  
  //Enter Mobile Number
  driver.findElement(By.id("phone_mobile")).sendKeys("234567890");
  driver.findElement(By.xpath("//input[@name=\"alias\"]")).clear();
  driver.findElement(By.xpath("//input[@name=\"alias\"]")).sendKeys("Office");
  driver.findElement(By.name("submitAccount")).click();
  String userText=driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a")).getText();

  // Validate that user has created
  if(userText.contains("Vsoft")) {
   System.out.println("User Verified,Test case Passed");
  }
  else {
   System.out.println("User Verification Failed,Test case Failed");
  }
 }
}

Negative Scenarios

2. Test Case - Verify invalid email address error.

Steps to Automate:
2. Click on the sign-in link.
3. Enter an invalid email address in the email box and click Enter.
4. Validate that an error message is displaying saying "Invalid email address."

3. Test Case - Verify error messages for mandatory fields.

Steps to Automate:
2. Click on the sign-in link.
3. Enter your email address and click the Register button.
4. Leave the mandatory fields (marked with *) blank and click the Register button.
5. Verify that an error has been displayed for the mandatory fields.

4. Test Case - Verify error messages for entering incorrect values in the fields.

Steps to Automate:
2. Click on the sign-in link.
3. Enter your email address and click the Register button.
4. Enter incorrect values in fields like., enter numbers in first and last name, city field, etc., and enter alphabets in Mobile no, Zip postal code, etc., and click on the 'Register' button.
5. Verify that error messages for respective fields are displaying.
Try automating the above scenarios using Selenium commands. If you face any difficulty, please refer to the Selenium Tutorial series.

2. Search Product Feature

1. Test Case - Automate the 'Search Product' feature of the e-commerce website with Selenium.

Steps to Automate:
2. Move your cursor over the Women's link.
3. Click on the sub-menu 'T-shirts'
4. Get the Name/Text of the first product displayed on the page.
5. Now, enter the same product name in the search bar present at the top of the page and click the search button.
6. Validate that the same product is displayed on the searched page with the same details that were displayed on the T-Shirt's page.

Automation Code for Product Search:

The following code is contributed by Uday.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

import io.github.bonigarcia.wdm.WebDriverManager;

public class EcomPractice2 {
 
 public static void main(String[] args) throws InterruptedException{

  WebDriverManager.chromedriver().setup();
  WebDriver driver=new ChromeDriver();
  String URL="http://automationpractice.com/index.php";

  driver.get(URL);
  driver.manage().window().maximize();
  
  // Initialise Actions class object
  Actions actions=new Actions(driver);
  driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
  WebElement womenTab=driver.findElement(By.linkText("WOMEN"));
  WebElement TshirtTab=driver.findElement(By.xpath("//div[@id='block_top_menu']/ul/li[1]/ul/li[1]/ul//a[@title='T-shirts']"));
  actions.moveToElement(womenTab).moveToElement(TshirtTab).click().perform();
  Thread.sleep(2000);
  
  // Get Product Name
  String ProductName=driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/div[3]/div[2]/ul[1]/li[1]/div[1]/div[2]/h5[1]/a[1]")).getText();
  System.out.println(ProductName);
  driver.findElement(By.id("search_query_top")).sendKeys(ProductName);
  driver.findElement(By.name("submit_search")).click();
  
  // Get Name of Searched Product
  String SearchResultProductname=driver.findElement(By.xpath("/html[1]/body[1]/div[1]/div[2]/div[1]/div[3]/div[2]/ul[1]/li[1]/div[1]/div[2]/h5[1]/a[1]")).getText();

  // Verify that correct Product is displaying after search
  if(ProductName.equalsIgnoreCase(SearchResultProductname)) {
   System.out.println("Results Matched;Test Case Passed");
  }else{
   System.out.println("Results NotMatched;Test Case Failed");
  }
  
  // Close the browser
  driver.close();
 }

}

3. Buy Product Feature

The most important function of an e-commerce website is buying a product, which includes various steps like selecting a product, selecting size/color, adding to the cart, checkout, etc. You will find every test scenario along with the automation code in the following section.

1. Test Case - Automate the end-to-end "Buy Product" feature

Steps to Automate:
2. Log in to the website.
3. Move your cursor over the Women's link.
4. Click on the sub-menu 'T-shirts'.
5. Mouse hover on the second product displayed.
6. The 'More' button will be displayed; click on the 'More' button.
7. Increase quantity to 2.
8. Select size 'L'
9. Select color.
10. Click the 'Add to Cart' button.
11. Click the 'Proceed to checkout' button.
12. Complete the buy order process till payment.
13. Make sure that the Product is ordered.

The following code for Purchase Product is contributed by Uday:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import io.github.bonigarcia.wdm.WebDriverManager;

public class EcomExpert {

 public static void main(String[] args){

  WebDriverManager.chromedriver().setup();
  WebDriver driver=new ChromeDriver();
  String URL="http://automationpractice.com/index.php";
  
  // Open URL and Maximize browser window
  driver.get(URL);
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);

  //Click on Sign in
  driver.findElement(By.linkText("Sign in")).click();
  //Login
  driver.findElement(By.id("email")).sendKeys("test1249@test.com");
  driver.findElement(By.id("passwd")).sendKeys("PKR@PKR");
  driver.findElement(By.id("SubmitLogin")).click();
  //Click on Women
  driver.findElement(By.linkText("WOMEN")).click();

  WebElement SecondImg=driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div[2]/ul/li[2]/div/div[1]/div/a[1]/img"));
  WebElement MoreBtn=driver.findElement(By.xpath("/html/body[1]/div[1]/div[2]/div[1]/div[3]/div[2]/ul/li[2]/div[1]/div[2]/div[2]/a[2]"));
  Actions actions=new Actions(driver);
  actions.moveToElement(SecondImg).moveToElement(MoreBtn).click().perform();

  //Change quantity by 2
  driver.findElement(By.id("quantity_wanted")).clear();
  driver.findElement(By.id("quantity_wanted")).sendKeys("2");

  //Select size as L
  WebElement Sizedrpdwn=driver.findElement(By.xpath("//*[@id='group_1']"));
  Select oSelect=new Select(Sizedrpdwn);
  oSelect.selectByVisibleText("M");

  //Select Color
  driver.findElement(By.id("color_11")).click();

  //Click on add to cart
  driver.findElement(By.xpath("//p[@id='add_to_cart']//span[.='Add to cart']")).click();

  //Click on proceed
  driver.findElement(By.xpath("/html//div[@id='layer_cart']//a[@title='Proceed to checkout']/span")).click();
  //Checkout page Proceed
  driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/p[2]/a[1]/span")).click();
  driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/form/p/button/span")).click();
  //Agree terms&Conditions
  driver.findElement(By.xpath("//*[@id=\"cgv\"]")).click();
  driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/div/form/p/button/span")).click();

  //Click on Payby Check
  driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/div/div[3]/div[2]/div/p/a")).click();
  //Confirm the order
  driver.findElement(By.xpath("/html/body/div[1]/div[2]/div/div[3]/div/form/p/button/span")).click();

  //Get Text
  String ConfirmationText=driver.findElement(By.xpath("//div[@id='center_column']/p[@class='alert alert-success']")).getText();
  
  // Verify that Product is ordered
  if(ConfirmationText.contains("complete")) {
   System.out.println("Order Completed: Test Case Passed");
  }
  else {
   System.out.println("Order Not Successfull: Test Case Failed");
  }

 }
}

You should try automating the below-mentioned scenarios yourself for your practice. You can also send your code to us via email or post it in the comments section. We would be happy to share your hard work on our website with your credentials. 

2. Test Case - Verify that 'Add to Wishlist' only works after login.

Steps to Automate:
2. Move your cursor over the Women's link.
3. Click on the sub-menu 'T-shirts'.
4. Mouse hover on the second product displayed.
5. 'Add to Wishlist' will appear at the bottom of that product; click on it.
6. Verify that the error message is displayed: 'You must be logged in to manage your wish list.'

3. Test Case - Verify that the Total Price reflects correctly if the user changes quantity on the 'Shopping Cart Summary' Page.

Steps to Automate:
2. Log in to the website.
3. Move your cursor over the Women's link.
4. Click on the sub-menu 'T-shirts'.
5. Mouse hover on the second product displayed.
6. The 'More' button will be displayed; click on the 'More' button.
7. Make sure the quantity is set to 1.
8. Select size 'M'
9. Select the color of your choice.
10. Click the 'Add to Cart' button.
11. Click the 'Proceed to checkout' button.
12. Change the quantity to 2.
13. Verify that the Total price is changing and reflecting the correct price.
Similar way, you can add a few more test cases.

4. Payment Gateway Integration

Simulate payment flows using test environments:

public void testPayment() {
    driver.findElement(By.id("checkoutButton")).click();
    driver.findElement(By.id("paymentOptionCard")).click();
    driver.findElement(By.id("payNowButton")).click();
    assert driver.findElement(By.id("confirmationMessage")).isDisplayed();
}

5. Order History

Ensure users can view past orders:

public void testOrderHistory() {
    driver.findElement(By.id("orderHistoryLink")).click();
    assert driver.findElements(By.className("orderItem")).size() > 0;
}

Best Practices for E-commerce Testing with Selenium

  1. Use Page Object Model (POM): Simplifies test maintenance by separating page structure from test logic.

  2. Parameterize Tests: Run the same test for different data sets using TestNG’s @DataProvider.

  3. Integrate with CI/CD: Execute tests automatically using Jenkins or GitHub Actions.

  4. Handle Dynamic Elements: Use XPath functions like contains() or starts-with() for dynamic locators.

  5. Implement Explicit Waits: Ensure elements are fully loaded before interacting with them.


Advanced Testing Scenarios

  1. Performance Testing: Measure page load times and responsiveness using tools like Selenium Grid.

  2. Security Testing: Verify that sensitive data (e.g., passwords, card details) is encrypted and secure.

  3. Multi-Browser Testing: Run tests across Chrome, Firefox, and Safari for compatibility.

  4. Localization Testing: Validate UI and content in different languages.


Tools to Complement Selenium for E-commerce Testing

  • JMeter: For load testing APIs and user workflows.

  • Postman: For API testing.

  • Allure: For generating detailed test reports.

  • Docker: To run Selenium tests in isolated containers.


Conclusion

Selenium automation is a powerful way to ensure the quality and reliability of e-commerce websites. By automating critical functionalities like login, search, and payment flows, testers can identify issues early and deliver a seamless user experience. Combine Selenium with complementary tools and follow best practices to build a robust automation framework.

Keywords: Selenium Automation, E-commerce Testing, Selenium Test Scenarios, Page Object Model, Test Automation Framework, Selenium with Java


You may also like to read:

Automate Google Search with Selenium << Previous  ||  Next>>  Automate Multiple Browser Tabs with Selenium

    Comments

    1. Great job for publishing such a nice article. Your article isn’t only useful but it is additionally really informative. Thank you because you have been willing to share information with us. Buy Internet Banking Php Script

      ReplyDelete
    2. You'll be able to make intelligent decisions to get your sites ranked higher, drive in more traffic, capture more leads and make more sales. inwap com

      ReplyDelete
    3. This is very informative and interesting platform for me to Build Your Own Website To Sell Products. Thank you for such a wonderful article and for sharing. God bless you.!

      ReplyDelete
    4. With fewer healthy people buying Insurance, and fewer Insurance companies offering it, the individual Insurance market would start to destabilize right away, potentially causing the perennially-discussed death spirals. What Is Citizen Insurance In Florida

      ReplyDelete
    5. Several automation aspects covered

      ReplyDelete
    6. The context of this content is really good. Thank you for sharing this type of awareness with us. In this article, you shared much informative knowledge on multiplication activities. Take look at this tooweb design agency dubai . Thanks!

      ReplyDelete
    7. Very useful post more cases like this travel websites and all

      ReplyDelete
    8. Wow, marvelous weblog layout! How lengthy have you been blogging for buy event product online in USA? you made blogging glance easy. The overall look of your website is fantastic, as well as the content!

      ReplyDelete

    Post a Comment

    Popular posts from this blog

    Top 10 Demo Websites for Selenium Automation Practice

    Mastering Selenium Practice: Automating Web Tables with Demo Examples

    25+ Selenium WebDriver Commands: The Complete Cheat Sheet with Examples

    Top 10 Highest Paid Indian-Origin CEOs in the USA: Leaders Shaping Industries

    AI and Machine Learning in Selenium Testing: Revolutionizing Test Automation

    14 Best Selenium Exercises to Master Automation Testing Skills

    Understanding Cryptocurrency: A Beginner's Guide to Bitcoin and Ethereum

    Best Budget Tech Gadgets You Can Buy in 2025

    Master Prompt Engineering: A Beginner's Guide to LLMs Like ChatGPT & Claude