Selenium Automation for E-commerce Websites
Table of Contents
Why Automate E-commerce Testing?
Modern e-commerce platforms are complex ecosystems integrating:
Product catalogs with thousands of dynamic SKUs
Multi-step shopping carts with real-time calculations
Secure payment gateways (credit cards, digital wallets)
User account systems with personalized experiences
Automation delivers transformative benefits:
Benefit | Impact | Example |
---|---|---|
Lightning-Fast Execution | 10-100x faster than manual testing | Run 500 product search tests in 15 minutes instead of 8 hours |
Flawless Precision | 99.9% error-free test execution | Eliminate checkout calculation mistakes during holiday sales |
Effortless Scalability | Test 10 or 10,000 products with equal ease | Handle Black Friday traffic spikes without additional resources |
Continuous Protection | Instant regression detection | Catch breaking changes before they reach production |
Real-world results from top retailers:
78% reduction in critical bugs reaching production
92% faster release cycles
$2.3M annual savings in QA costs (Forrester Research)
"Automation isn't just about speed - it's about building trust in every customer interaction." - Amazon QA Director
This strategic approach transforms testing from a bottleneck to a competitive advantage, ensuring seamless customer experiences at scale.
Key Challenges in E-commerce Testing
Challenge Solution Dynamic Content (Prices, Offers) Use XPath/CSS Selectors with contains()
, starts-with()
Third-party Integrations (Payment Gateways, APIs) Mock APIs using Postman or RestAssured Responsive Design Cross-browser testing with Selenium Grid High Traffic Handling Load testing with JMeter
Challenge | Solution |
---|---|
Dynamic Content (Prices, Offers) | Use XPath/CSS Selectors with contains() , starts-with() |
Third-party Integrations (Payment Gateways, APIs) | Mock APIs using Postman or RestAssured |
Responsive Design | Cross-browser testing with Selenium Grid |
High Traffic Handling | Load testing with JMeter |
Prerequisites for Automation
You should know the following topics before starting this project assignment:
- Core Java (for Selenium scripting)
- Locators (Xpath, CSS Selectors)
Test Scenarios for E-commerce Websites
1. User Registration & Login
Test Cases
Scenario | Expected Result |
---|---|
Guest checkout | Allows purchase without registration |
Valid registration | User account created successfully |
Invalid email format | Shows error message |
Mandatory field validation | Prevents submission with blank fields |
Complete Registration Test Automation Suite
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 EcommerceRegistrationTest {
public static void main(String[] args) {
// Initialize WebDriver
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
try {
// Test Configuration
String URL = "http://automationpractice.com/index.php";
String testEmail = "test" + System.currentTimeMillis() + "@test.com";
// Test Execution
driver.get(URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
// Registration Flow
driver.findElement(By.linkText("Sign in")).click();
driver.findElement(By.cssSelector("[name='email_create']")).sendKeys(testEmail);
driver.findElement(By.xpath("//button[@name='SubmitCreate']")).click();
// Fill Registration Form
fillRegistrationForm(driver);
// Validation
String userName = driver.findElement(By.cssSelector(".account")).getText();
if(userName.contains("Vsoft")) {
System.out.println("Registration Successful - Test Passed");
} else {
System.out.println("Registration Failed - Test Failed");
}
} finally {
driver.quit();
}
}
private static void fillRegistrationForm(WebDriver driver) {
// Personal Information
driver.findElement(By.id("id_gender1")).click();
driver.findElement(By.name("customer_firstname")).sendKeys("Test");
driver.findElement(By.name("customer_lastname")).sendKeys("User");
driver.findElement(By.id("passwd")).sendKeys("Password@123");
// Address Information
driver.findElement(By.id("address1")).sendKeys("123 Test St");
driver.findElement(By.id("city")).sendKeys("Testville");
// State Selection
Select stateDropdown = new Select(driver.findElement(By.name("id_state")));
stateDropdown.selectByValue("4");
driver.findElement(By.id("postcode")).sendKeys("12345");
driver.findElement(By.id("phone_mobile")).sendKeys("1234567890");
driver.findElement(By.name("submitAccount")).click();
}
}
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 EcommerceRegistrationTest { public static void main(String[] args) { // Initialize WebDriver WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); try { // Test Configuration String URL = "http://automationpractice.com/index.php"; String testEmail = "test" + System.currentTimeMillis() + "@test.com"; // Test Execution driver.get(URL); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); // Registration Flow driver.findElement(By.linkText("Sign in")).click(); driver.findElement(By.cssSelector("[name='email_create']")).sendKeys(testEmail); driver.findElement(By.xpath("//button[@name='SubmitCreate']")).click(); // Fill Registration Form fillRegistrationForm(driver); // Validation String userName = driver.findElement(By.cssSelector(".account")).getText(); if(userName.contains("Vsoft")) { System.out.println("Registration Successful - Test Passed"); } else { System.out.println("Registration Failed - Test Failed"); } } finally { driver.quit(); } } private static void fillRegistrationForm(WebDriver driver) { // Personal Information driver.findElement(By.id("id_gender1")).click(); driver.findElement(By.name("customer_firstname")).sendKeys("Test"); driver.findElement(By.name("customer_lastname")).sendKeys("User"); driver.findElement(By.id("passwd")).sendKeys("Password@123"); // Address Information driver.findElement(By.id("address1")).sendKeys("123 Test St"); driver.findElement(By.id("city")).sendKeys("Testville"); // State Selection Select stateDropdown = new Select(driver.findElement(By.name("id_state"))); stateDropdown.selectByValue("4"); driver.findElement(By.id("postcode")).sendKeys("12345"); driver.findElement(By.id("phone_mobile")).sendKeys("1234567890"); driver.findElement(By.name("submitAccount")).click(); } }
Negative Test Scenarios
1. Invalid Email Format Validation
@Test
public void testInvalidEmailRegistration() {
driver.findElement(By.linkText("Sign in")).click();
driver.findElement(By.id("email_create")).sendKeys("invalid-email");
driver.findElement(By.id("SubmitCreate")).click();
String errorMessage = driver.findElement(By.id("create_account_error")).getText();
Assert.assertTrue(errorMessage.contains("Invalid email address"));
}
@Test public void testInvalidEmailRegistration() { driver.findElement(By.linkText("Sign in")).click(); driver.findElement(By.id("email_create")).sendKeys("invalid-email"); driver.findElement(By.id("SubmitCreate")).click(); String errorMessage = driver.findElement(By.id("create_account_error")).getText(); Assert.assertTrue(errorMessage.contains("Invalid email address")); }
2. Mandatory Field Validation
@Test
public void testMandatoryFieldValidation() {
// Start registration with valid email
driver.findElement(By.linkText("Sign in")).click();
driver.findElement(By.id("email_create")).sendKeys("test" + System.currentTimeMillis() + "@test.com");
driver.findElement(By.id("SubmitCreate")).click();
// Submit empty form
driver.findElement(By.id("submitAccount")).click();
// Verify error count
int errorCount = driver.findElements(By.cssSelector(".alert-danger li")).size();
Assert.assertTrue(errorCount > 0);
}
@Test public void testMandatoryFieldValidation() { // Start registration with valid email driver.findElement(By.linkText("Sign in")).click(); driver.findElement(By.id("email_create")).sendKeys("test" + System.currentTimeMillis() + "@test.com"); driver.findElement(By.id("SubmitCreate")).click(); // Submit empty form driver.findElement(By.id("submitAccount")).click(); // Verify error count int errorCount = driver.findElements(By.cssSelector(".alert-danger li")).size(); Assert.assertTrue(errorCount > 0); }
3. Invalid Data Format Validation
@Test
public void testInvalidDataFormats() {
// Start registration
// ...
// Enter invalid data
driver.findElement(By.id("firstname")).sendKeys("12345"); // Numbers in name field
driver.findElement(By.id("postcode")).sendKeys("ABCDE"); // Letters in zip code
driver.findElement(By.id("submitAccount")).click();
Assert.assertTrue(driver.findElement(By.cssSelector(".alert-danger"))
.getText().contains("invalid"));
}
@Test public void testInvalidDataFormats() { // Start registration // ... // Enter invalid data driver.findElement(By.id("firstname")).sendKeys("12345"); // Numbers in name field driver.findElement(By.id("postcode")).sendKeys("ABCDE"); // Letters in zip code driver.findElement(By.id("submitAccount")).click(); Assert.assertTrue(driver.findElement(By.cssSelector(".alert-danger")) .getText().contains("invalid")); }
2. Product Search Feature for E-commerce
Test Cases
Scenario | Expected Result |
---|---|
Search with filters (Price, Brand) | Displays relevant products |
Empty search query | Shows "No results found" |
Partial keyword search | Returns matching products |
Automation Test Suite for Product Search for E-commerce Website
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; import java.time.Duration; public class ProductSearchTest { private static final String BASE_URL = "http://automationpractice.com/index.php"; private static final Duration TIMEOUT = Duration.ofSeconds(10); public static void main(String[] args) { // Initialize WebDriver with automatic browser management WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, TIMEOUT); Actions actions = new Actions(driver); try { // Test Configuration driver.manage().window().maximize(); driver.get(BASE_URL); // 1. Navigate to T-Shirts category navigateToTShirtsCategory(driver, wait, actions); // 2. Capture product details String productName = captureFirstProductName(driver, wait); // 3. Execute search and validate validateProductSearch(driver, wait, productName); } finally { driver.quit(); } } private static void navigateToTShirtsCategory(WebDriver driver, WebDriverWait wait, Actions actions) { WebElement womenMenu = wait.until(ExpectedConditions.elementToBeClickable( By.linkText("WOMEN"))); WebElement tshirtsSubmenu = wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//ul[contains(@class,'submenu-container')]//a[@title='T-shirts']"))); actions.moveToElement(womenMenu) .pause(Duration.ofMillis(500)) .click(tshirtsSubmenu) .perform(); } private static String captureFirstProductName(WebDriver driver, WebDriverWait wait) { WebElement firstProduct = wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//ul[@class='product_list']/li[1]//h5/a"))); String productName = firstProduct.getText().trim(); System.out.println("Captured Product: " + productName); return productName; } private static void validateProductSearch(WebDriver driver, WebDriverWait wait, String productName) { WebElement searchField = wait.until(ExpectedConditions.elementToBeClickable( By.id("search_query_top"))); searchField.sendKeys(productName); driver.findElement(By.name("submit_search")).click(); // Verification WebElement searchResult = wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//ul[@class='product_list']/li[1]//h5/a"))); String resultProductName = searchResult.getText().trim(); if (productName.equalsIgnoreCase(resultProductName)) { System.out.println("✅ Search Validation Passed - Correct product displayed"); } else { System.out.println("❌ Search Validation Failed"); System.out.println("Expected: " + productName); System.out.println("Actual: " + resultProductName); } } }
Here's a concise explanation of the Selenium test code:
Purpose: This automated test verifies product search functionality on an e-commerce site.
Key Components:
Setup:
Uses ChromeDriver via WebDriverManager
Configures 10-second timeout for element waits
Initializes Actions class for mouse interactions
Test Flow:
Navigates to the website homepage
Hovers over "WOMEN" menu and clicks "T-shirts" submenu
Captures the name of the first displayed product
Searches for that product name
Verifies the search returns the correct product
Helper Methods:
navigateToTShirtsCategory()
: Handles menu navigationcaptureFirstProductName()
: Gets product textvalidateProductSearch()
: Performs search and validation
Cleanup:
Automatically closes browser when done
Uses try-finally to ensure cleanup
What It Validates:
Category navigation works
Product names display correctly
Search functionality returns accurate results
UI elements are interactable
3. Product Details and Cart Management
Test Cases
Scenario Expected Result Add to cart Product appears in cart Update quantity Total price recalculates Remove item Cart updates correctly
Scenario | Expected Result |
---|---|
Add to cart | Product appears in cart |
Update quantity | Total price recalculates |
Remove item | Cart updates correctly |
Purchase Product Test Automation Suite for E-commerce Website
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import static org.junit.Assert.*;
public class EcommercePurchaseTest {
private static final String BASE_URL = "http://automationpractice.com/index.php";
private static final String USER_EMAIL = "testuser_" + System.currentTimeMillis() + "@test.com";
private static final String PASSWORD = "SecurePass123!";
private static final Duration TIMEOUT = Duration.ofSeconds(10);
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
Actions actions = new Actions(driver);
try {
// Test Setup
driver.manage().window().maximize();
driver.get(BASE_URL);
// 1. User Login
loginToAccount(driver, wait);
// 2. Select Product
selectProduct(driver, wait, actions);
// 3. Configure Product Options
configureProduct(driver, wait);
// 4. Complete Checkout Process
completeCheckout(driver, wait);
// 5. Verify Order Confirmation
verifyOrderConfirmation(driver, wait);
} finally {
driver.quit();
}
}
private static void loginToAccount(WebDriver driver, WebDriverWait wait) {
driver.findElement(By.linkText("Sign in")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));
driver.findElement(By.id("email")).sendKeys(USER_EMAIL);
driver.findElement(By.id("passwd")).sendKeys(PASSWORD);
driver.findElement(By.id("SubmitLogin")).click();
assertTrue(driver.findElement(By.cssSelector(".account")).isDisplayed());
}
private static void selectProduct(WebDriver driver, WebDriverWait wait, Actions actions) {
WebElement womenMenu = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("WOMEN")));
WebElement tshirtsSubmenu = driver.findElement(By.xpath("//ul[contains(@class,'submenu-container')]//a[@title='T-shirts']"));
actions.moveToElement(womenMenu)
.pause(Duration.ofMillis(500))
.click(tshirtsSubmenu)
.perform();
WebElement product = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//ul[@class='product_list']/li[2]")));
WebElement moreButton = product.findElement(By.xpath(".//a[contains(@class,'lnk_view')]"));
actions.moveToElement(product)
.pause(Duration.ofMillis(500))
.click(moreButton)
.perform();
}
private static void configureProduct(WebDriver driver, WebDriverWait wait) {
// Set quantity
WebElement quantity = wait.until(ExpectedConditions.elementToBeClickable(By.id("quantity_wanted")));
quantity.clear();
quantity.sendKeys("2");
// Select size
Select sizeDropdown = new Select(driver.findElement(By.id("group_1")));
sizeDropdown.selectByVisibleText("M");
// Select color
driver.findElement(By.id("color_11")).click();
// Add to cart
driver.findElement(By.xpath("//button[contains(@class,'add_to_cart')]")).click();
// Wait for cart overlay and proceed
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//div[contains(@class,'layer_cart_product')]")));
driver.findElement(By.xpath("//a[@title='Proceed to checkout']")).click();
}
private static void completeCheckout(WebDriver driver, WebDriverWait wait) {
// Proceed through checkout steps
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//p[@class='cart_navigation clearfix']/a[@title='Proceed to checkout']")))
.click();
wait.until(ExpectedConditions.elementToBeClickable(By.name("processAddress"))).click();
driver.findElement(By.id("cgv")).click();
driver.findElement(By.name("processCarrier")).click();
// Select payment method
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//a[@title='Pay by check.']")))
.click();
// Confirm order
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//button[contains(@class,'button-medium')]")))
.click();
}
private static void verifyOrderConfirmation(WebDriver driver, WebDriverWait wait) {
WebElement confirmation = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//p[@class='alert alert-success']")));
assertTrue("Order confirmation not displayed",
confirmation.getText().contains("complete"));
System.out.println("✅ Order completed successfully");
}
}
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; import java.time.Duration; import static org.junit.Assert.*; public class EcommercePurchaseTest { private static final String BASE_URL = "http://automationpractice.com/index.php"; private static final String USER_EMAIL = "testuser_" + System.currentTimeMillis() + "@test.com"; private static final String PASSWORD = "SecurePass123!"; private static final Duration TIMEOUT = Duration.ofSeconds(10); public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, TIMEOUT); Actions actions = new Actions(driver); try { // Test Setup driver.manage().window().maximize(); driver.get(BASE_URL); // 1. User Login loginToAccount(driver, wait); // 2. Select Product selectProduct(driver, wait, actions); // 3. Configure Product Options configureProduct(driver, wait); // 4. Complete Checkout Process completeCheckout(driver, wait); // 5. Verify Order Confirmation verifyOrderConfirmation(driver, wait); } finally { driver.quit(); } } private static void loginToAccount(WebDriver driver, WebDriverWait wait) { driver.findElement(By.linkText("Sign in")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email"))); driver.findElement(By.id("email")).sendKeys(USER_EMAIL); driver.findElement(By.id("passwd")).sendKeys(PASSWORD); driver.findElement(By.id("SubmitLogin")).click(); assertTrue(driver.findElement(By.cssSelector(".account")).isDisplayed()); } private static void selectProduct(WebDriver driver, WebDriverWait wait, Actions actions) { WebElement womenMenu = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("WOMEN"))); WebElement tshirtsSubmenu = driver.findElement(By.xpath("//ul[contains(@class,'submenu-container')]//a[@title='T-shirts']")); actions.moveToElement(womenMenu) .pause(Duration.ofMillis(500)) .click(tshirtsSubmenu) .perform(); WebElement product = wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//ul[@class='product_list']/li[2]"))); WebElement moreButton = product.findElement(By.xpath(".//a[contains(@class,'lnk_view')]")); actions.moveToElement(product) .pause(Duration.ofMillis(500)) .click(moreButton) .perform(); } private static void configureProduct(WebDriver driver, WebDriverWait wait) { // Set quantity WebElement quantity = wait.until(ExpectedConditions.elementToBeClickable(By.id("quantity_wanted"))); quantity.clear(); quantity.sendKeys("2"); // Select size Select sizeDropdown = new Select(driver.findElement(By.id("group_1"))); sizeDropdown.selectByVisibleText("M"); // Select color driver.findElement(By.id("color_11")).click(); // Add to cart driver.findElement(By.xpath("//button[contains(@class,'add_to_cart')]")).click(); // Wait for cart overlay and proceed wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//div[contains(@class,'layer_cart_product')]"))); driver.findElement(By.xpath("//a[@title='Proceed to checkout']")).click(); } private static void completeCheckout(WebDriver driver, WebDriverWait wait) { // Proceed through checkout steps wait.until(ExpectedConditions.elementToBeClickable( By.xpath("//p[@class='cart_navigation clearfix']/a[@title='Proceed to checkout']"))) .click(); wait.until(ExpectedConditions.elementToBeClickable(By.name("processAddress"))).click(); driver.findElement(By.id("cgv")).click(); driver.findElement(By.name("processCarrier")).click(); // Select payment method wait.until(ExpectedConditions.elementToBeClickable( By.xpath("//a[@title='Pay by check.']"))) .click(); // Confirm order wait.until(ExpectedConditions.elementToBeClickable( By.xpath("//button[contains(@class,'button-medium')]"))) .click(); } private static void verifyOrderConfirmation(WebDriver driver, WebDriverWait wait) { WebElement confirmation = wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//p[@class='alert alert-success']"))); assertTrue("Order confirmation not displayed", confirmation.getText().contains("complete")); System.out.println("✅ Order completed successfully"); } }
Here's a concise explanation of the e-commerce purchase test automation code:
Purpose: Automates an end-to-end product purchase workflow including login, product selection, checkout, and payment.
Key Components:
Setup:
Configures ChromeDriver with 10-second timeouts
Generates unique test credentials using timestamps
Initializes WebDriver, WebDriverWait, and Actions
Test Flow:
Logs in with test credentials
Navigates to Women > T-shirts category
Selects second product and views details
Configures product options (quantity: 2, size: M, color)
Adds to cart and proceeds through checkout
Selects "Pay by check" and confirms order
Verifies successful order confirmation
Key Methods:
loginToAccount()
: Handles authenticationselectProduct()
: Navigates category menusconfigureProduct()
: Sets product optionscompleteCheckout()
: Processes paymentverifyOrderConfirmation()
: Validates success
4. Payment and Order History
Test Cases
Scenario Expected Result Guest checkout Allows purchase without login Payment failure Displays error message Order confirmation Sends email/SMS confirmation
Scenario | Expected Result |
---|---|
Guest checkout | Allows purchase without login |
Payment failure | Displays error message |
Order confirmation | Sends email/SMS confirmation |
Payment Gateway Automation Test Suite for E-commerce Website
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import static org.junit.Assert.*;
public class PaymentGatewayTests {
private static final String TEST_URL = "https://sandbox.example-ecom.com";
private static final Duration TIMEOUT = Duration.ofSeconds(15);
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
try {
driver.manage().window().maximize();
driver.get(TEST_URL);
// Run payment tests
testCreditCardPayment(driver, wait);
testPayPalPayment(driver, wait);
// Verify order history
testOrderHistoryVisibility(driver, wait);
} finally {
driver.quit();
}
}
// Payment Test Methods
private static void testCreditCardPayment(WebDriver driver, WebDriverWait wait) {
navigateToCheckout(driver, wait);
selectPaymentMethod(driver, wait, "card");
fillCardDetails(driver, wait, "4111111111111111", "12/25", "123");
submitPayment(driver, wait);
verifyConfirmation(driver, wait, "Credit Card");
}
private static void testPayPalPayment(WebDriver driver, WebDriverWait wait) {
navigateToCheckout(driver, wait);
selectPaymentMethod(driver, wait, "paypal");
driver.findElement(By.id("paypalLoginButton")).click();
// Switch to PayPal iframe
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.cssSelector("iframe[name='paypal']")));
// Sandbox credentials
wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("sb-test@example.com");
driver.findElement(By.id("password")).sendKeys("test1234");
driver.findElement(By.id("btnLogin")).click();
driver.switchTo().defaultContent();
submitPayment(driver, wait);
verifyConfirmation(driver, wait, "PayPal");
}
// Order History Test
private static void testOrderHistoryVisibility(WebDriver driver, WebDriverWait wait) {
driver.findElement(By.cssSelector(".account-dropdown")).click();
wait.until(ExpectedConditions.elementToBeClickable(
By.linkText("Order History"))).click();
WebElement orderTable = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".order-history-table")));
assertTrue("No orders found in history",
orderTable.findElements(By.cssSelector(".order-item")).size() > 0);
System.out.println("✅ Order history verification passed");
}
// Helper Methods
private static void navigateToCheckout(WebDriver driver, WebDriverWait wait) {
driver.findElement(By.cssSelector(".mini-cart")).click();
wait.until(ExpectedConditions.elementToBeClickable(
By.id("proceedToCheckout"))).click();
}
private static void selectPaymentMethod(WebDriver driver, WebDriverWait wait, String method) {
String selector = String.format("input[value='%s']", method);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(selector))).click();
}
private static void fillCardDetails(WebDriver driver, WebDriverWait wait,
String cardNumber, String expiry, String cvv) {
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(
By.cssSelector(".card-number-frame")));
driver.findElement(By.name("cardnumber")).sendKeys(cardNumber);
driver.switchTo().defaultContent();
// Similar handling for expiry and CVV iframes
// ...
}
private static void submitPayment(WebDriver driver, WebDriverWait wait) {
wait.until(ExpectedConditions.elementToBeClickable(
By.id("submitPayment"))).click();
}
private static void verifyConfirmation(WebDriver driver, WebDriverWait wait, String method) {
WebElement confirmation = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".payment-confirmation")));
assertTrue(String.format("%s payment failed", method),
confirmation.getText().contains("successful"));
System.out.println("✅ " + method + " payment test passed");
}
}
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import io.github.bonigarcia.wdm.WebDriverManager; import java.time.Duration; import static org.junit.Assert.*; public class PaymentGatewayTests { private static final String TEST_URL = "https://sandbox.example-ecom.com"; private static final Duration TIMEOUT = Duration.ofSeconds(15); public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, TIMEOUT); try { driver.manage().window().maximize(); driver.get(TEST_URL); // Run payment tests testCreditCardPayment(driver, wait); testPayPalPayment(driver, wait); // Verify order history testOrderHistoryVisibility(driver, wait); } finally { driver.quit(); } } // Payment Test Methods private static void testCreditCardPayment(WebDriver driver, WebDriverWait wait) { navigateToCheckout(driver, wait); selectPaymentMethod(driver, wait, "card"); fillCardDetails(driver, wait, "4111111111111111", "12/25", "123"); submitPayment(driver, wait); verifyConfirmation(driver, wait, "Credit Card"); } private static void testPayPalPayment(WebDriver driver, WebDriverWait wait) { navigateToCheckout(driver, wait); selectPaymentMethod(driver, wait, "paypal"); driver.findElement(By.id("paypalLoginButton")).click(); // Switch to PayPal iframe wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt( By.cssSelector("iframe[name='paypal']"))); // Sandbox credentials wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("sb-test@example.com"); driver.findElement(By.id("password")).sendKeys("test1234"); driver.findElement(By.id("btnLogin")).click(); driver.switchTo().defaultContent(); submitPayment(driver, wait); verifyConfirmation(driver, wait, "PayPal"); } // Order History Test private static void testOrderHistoryVisibility(WebDriver driver, WebDriverWait wait) { driver.findElement(By.cssSelector(".account-dropdown")).click(); wait.until(ExpectedConditions.elementToBeClickable( By.linkText("Order History"))).click(); WebElement orderTable = wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".order-history-table"))); assertTrue("No orders found in history", orderTable.findElements(By.cssSelector(".order-item")).size() > 0); System.out.println("✅ Order history verification passed"); } // Helper Methods private static void navigateToCheckout(WebDriver driver, WebDriverWait wait) { driver.findElement(By.cssSelector(".mini-cart")).click(); wait.until(ExpectedConditions.elementToBeClickable( By.id("proceedToCheckout"))).click(); } private static void selectPaymentMethod(WebDriver driver, WebDriverWait wait, String method) { String selector = String.format("input[value='%s']", method); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(selector))).click(); } private static void fillCardDetails(WebDriver driver, WebDriverWait wait, String cardNumber, String expiry, String cvv) { wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt( By.cssSelector(".card-number-frame"))); driver.findElement(By.name("cardnumber")).sendKeys(cardNumber); driver.switchTo().defaultContent(); // Similar handling for expiry and CVV iframes // ... } private static void submitPayment(WebDriver driver, WebDriverWait wait) { wait.until(ExpectedConditions.elementToBeClickable( By.id("submitPayment"))).click(); } private static void verifyConfirmation(WebDriver driver, WebDriverWait wait, String method) { WebElement confirmation = wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".payment-confirmation"))); assertTrue(String.format("%s payment failed", method), confirmation.getText().contains("successful")); System.out.println("✅ " + method + " payment test passed"); } }
This Java Selenium script automates payment gateway testing for an e-commerce website, covering credit card and PayPal transactions, plus order history verification.
Key Components
Setup
Uses ChromeDriver via WebDriverManager
Sets 15-second timeout for element waits
Tests run on a sandbox environment (
TEST_URL
)
Test Workflow
Credit Card Payment Test
Enters test card details (
4111...
visa test number)Submits payment and verifies confirmation
PayPal Sandbox Test
Switches to PayPal iframe
Logs in with sandbox credentials
Completes payment flow
Order History Check
Verifies orders appear in purchase history
Helper Methods
navigateToCheckout()
: Goes from cart to checkoutselectPaymentMethod()
: Chooses card/PayPal optionfillCardDetails()
: Handles iframe entry for card datasubmitPayment()
: Clicks payment buttonverifyConfirmation()
: Checks for success message
Why This Matters
Sandbox Testing: Uses test payment credentials (no real money)
Iframe Handling: Properly switches contexts for payment forms
Modular Design: Reusable methods for different payment types
Validation: Asserts confirmations and order history updates
Additional Test Scenarios
1. Failed Payment Simulation
@Test public void testDeclinedCardPayment() { navigateToCheckout(driver, wait); selectPaymentMethod(driver, wait, "card"); fillCardDetails(driver, wait, "4000000000000002", "12/25", "123"); submitPayment(driver, wait); WebElement error = wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".payment-error"))); assertTrue(error.getText().contains("declined")); }
2. Order Details Verification
@Test public void testOrderDetailsAccuracy() { navigateToOrderHistory(driver, wait); WebElement firstOrder = driver.findElement( By.cssSelector(".order-item:first-child")); firstOrder.click(); WebElement productName = wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".product-name"))); WebElement totalAmount = driver.findElement(By.cssSelector(".order-total")); assertEquals("Printed Summer Dress", productName.getText()); assertEquals("$58.50", totalAmount.getText()); }
Best Practices for E-commerce Test Automation
Use Page Object Model (POM): Simplifies test maintenance by separating page structure from test logic.
Parameterize Tests: Run the same test for different data sets using TestNG’s
@DataProvider
.Integrate with CI/CD: Execute tests automatically using Jenkins or GitHub Actions.
Handle Dynamic Elements: Use XPath functions like
contains()
orstarts-with()
for dynamic locators.Implement Explicit Waits: Ensure elements are fully loaded before interacting with them.
Advanced Testing Scenarios
Performance Testing (JMeter + Selenium)
Security Testing (OWASP ZAP for vulnerability scans)
Localization Testing (Multi-language support validation)
Performance Testing (JMeter + Selenium)
Security Testing (OWASP ZAP for vulnerability scans)
Localization Testing (Multi-language support validation)
Complementary Tools for E-commerce Testing
Tool Purpose JMeter Load & performance testing Postman API testing Allure Reports Detailed test reporting Docker Containerized test execution
Tool | Purpose |
---|---|
JMeter | Load & performance testing |
Postman | API testing |
Allure Reports | Detailed test reporting |
Docker | Containerized test execution |
Conclusion
Automating e-commerce testing with Selenium ensures faster releases, fewer bugs, and better user experience. By following best practices and leveraging tools like TestNG, POM, and CI/CD, teams can achieve scalable and maintainable test automation.