Popular Searches
Popular Course Categories
Popular Courses

Shopping Cart Automation

Shopping Cart Automation

Real-World Selenium Projects

Shopping Cart Automation Using Selenium WebDriver

Shopping Cart Automation is the process of automating an e-commerce shopping workflow using Selenium WebDriver. It involves validating important user actions such as searching for products, viewing product details, adding products to the cart, updating quantities, removing products, verifying prices and totals, and proceeding toward checkout.

Shopping cart automation is an important real-world Selenium project because it combines multiple automation concepts including locators, WebDriver commands, waits, assertions, Page Object Model, reusable methods, test data, TestNG, screenshots, and end-to-end test execution.

In a Selenium automation framework, shopping cart functionality can be divided into reusable page classes such as LoginPage, HomePage, ProductPage, CartPage, and CheckoutPage. This approach keeps page-specific locators and actions separate from test cases.

Course Resource: Selenium Training | Register for Selenium Course Demo


1. What is Shopping Cart Automation?

Shopping Cart Automation is the use of automated testing tools such as Selenium WebDriver to verify the functionality of an e-commerce application's shopping cart.

Instead of manually performing every shopping action, Selenium interacts with the application automatically and verifies whether the application behaves as expected.

A typical automated shopping cart workflow is:

Open Application

        |

        v

Login

        |

        v

Search Product

        |

        v

Open Product

        |

        v

Add Product to Cart

        |

        v

Open Shopping Cart

        |

        v

Verify Product

        |

        v

Update Quantity

        |

        v

Verify Price and Total

        |

        v

Remove Product

        |

        v

Proceed to Checkout

        |

        v

Verify Checkout


2. Why Automate Shopping Cart Testing?

E-commerce applications contain many repetitive user workflows. Manual testing of every product, quantity, discount, and cart combination can consume significant time.

  • Reduces repetitive manual testing.
  • Improves test execution speed.
  • Allows repeated regression testing.
  • Validates important business workflows.
  • Improves test coverage.
  • Supports data-driven testing.
  • Can be integrated with CI/CD pipelines.
  • Helps detect UI and functional defects earlier.
  • Supports cross-browser testing.
  • Provides repeatable test execution.


3. Shopping Cart Testing Scope

A complete shopping cart automation suite can cover multiple functional areas.

AreaExample Validation
Product SearchVerify that the requested product can be found.
Product DetailsVerify product name, price, image, and details.
Add to CartVerify the selected product is added.
Cart CountVerify the cart item count is updated.
QuantityVerify quantity can be increased or decreased.
PriceVerify product price.
TotalVerify quantity multiplied by price.
Remove ProductVerify the selected product can be removed.
Multiple ProductsVerify several products can coexist in the cart.
CheckoutVerify that the user can proceed toward checkout.


4. Functional Shopping Cart Scenarios

Common functional scenarios include:

  1. Add one product to the cart.
  2. Add multiple products to the cart.
  3. Add the same product more than once.
  4. Increase product quantity.
  5. Decrease product quantity.
  6. Remove a product.
  7. Remove all products.
  8. Verify cart count.
  9. Verify product name.
  10. Verify product price.
  11. Verify subtotal.
  12. Verify total amount.
  13. Apply a discount or coupon.
  14. Verify discount calculation.
  15. Proceed to checkout.
  16. Verify cart persistence after navigation.


5. Shopping Cart Automation Architecture

TestNG Test Class

        |

        v

Page Object Classes

        |

        +---- HomePage

        |

        +---- ProductPage

        |

        +---- CartPage

        |

        +---- CheckoutPage

        |

        v

Selenium WebDriver

        |

        v

Browser

        |

        v

E-Commerce Application


6. Tools and Technologies

TechnologyPurpose
JavaProgramming language for automation.
Selenium WebDriverBrowser automation.
TestNGTest execution and assertions.
MavenDependency and build management.
Page Object ModelFramework organization and maintainability.
WebDriverWaitSynchronization with dynamic elements.
ExtentReports/AllureOptional test reporting.
GitSource-code version control.


7. Setting Up Selenium WebDriver

A basic Selenium test requires a WebDriver instance. The driver is responsible for communicating with the selected browser.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class CartTest {

    WebDriver driver;

 

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

    }

}

The URL in the example should be replaced with the application URL used by the automation project.


8. Identifying Shopping Cart Elements

Before automating a shopping cart, identify the important elements on the application.

ElementPossible Locator
Search Boxid, name, CSS Selector
Search Buttonid, class, CSS Selector
Product NameCSS Selector, XPath
Product PriceCSS Selector, XPath
Add to Cartid, CSS Selector, XPath
Cart Iconid, class, CSS Selector
Quantity Fieldid, name, CSS Selector
Remove ButtonCSS Selector, XPath
Checkout Buttonid, CSS Selector


9. Creating a Product Page Class

The Product Page class should contain product-related locators and reusable methods.

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class ProductPage {

 

    private WebDriver driver;

 

    private By productName =

            By.id("productName");

 

    private By productPrice =

            By.id("productPrice");

 

    private By addToCartButton =

            By.id("addToCart");

 

    public ProductPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public String getProductName() {

        return driver.findElement(productName).getText();

    }

 

    public String getProductPrice() {

        return driver.findElement(productPrice).getText();

    }

 

    public void addToCart() {

        driver.findElement(addToCartButton).click();

    }

}


10. Creating a Cart Page Class

The CartPage class contains the locators and actions related to the shopping cart.

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class CartPage {

 

    private WebDriver driver;

 

    private By cartProduct =

            By.id("cartProduct");

 

    private By quantityField =

            By.id("quantity");

 

    private By removeButton =

            By.id("removeProduct");

 

    private By cartTotal =

            By.id("cartTotal");

 

    private By checkoutButton =

            By.id("checkout");

 

    public CartPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public String getProductName() {

        return driver.findElement(cartProduct).getText();

    }

 

    public void updateQuantity(String quantity) {

        driver.findElement(quantityField).clear();

        driver.findElement(quantityField).sendKeys(quantity);

    }

 

    public void removeProduct() {

        driver.findElement(removeButton).click();

    }

 

    public String getCartTotal() {

        return driver.findElement(cartTotal).getText();

    }

 

    public void clickCheckout() {

        driver.findElement(checkoutButton).click();

    }

}


11. Opening the Shopping Cart

The automation script should be able to navigate from the product page to the shopping cart.

private By cartIcon =

        By.id("cart");

 

public void openCart() {

    driver.findElement(cartIcon).click();

}


12. Adding a Product to Cart

The basic add-to-cart operation involves locating the product and clicking the Add to Cart button.

driver.findElement(By.id("addToCart")).click();

After clicking the button, the automation should verify that the application actually added the product.


13. Verifying Product Added to Cart

After adding a product, the test should validate the cart contents instead of assuming that the operation succeeded.

CartPage cartPage = new CartPage(driver);

 

String productName = cartPage.getProductName();

 

Assert.assertEquals(

    productName,

    "Laptop"

);


14. Verifying Cart Count

Many e-commerce applications display the number of products or items in the shopping cart.

By cartCount = By.id("cartCount");

 

String count =

        driver.findElement(cartCount).getText();

 

Assert.assertEquals(count, "1");


15. Adding Multiple Products

Multiple products can be added sequentially and then validated inside the cart.

driver.findElement(By.id("laptopAdd")).click();

driver.findElement(By.id("mobileAdd")).click();

driver.findElement(By.id("headphonesAdd")).click();

The cart should then be opened and each product should be verified.


16. Adding the Same Product Multiple Times

An important cart scenario is adding the same product more than once. Depending on application behavior, the cart may increase the quantity or create separate cart lines.

driver.findElement(By.id("addToCart")).click();

driver.findElement(By.id("addToCart")).click();

The expected behavior should be defined by the application's requirements.


17. Updating Product Quantity

Quantity validation is an important shopping cart test scenario.

By quantityField =

        By.id("quantity");

 

driver.findElement(quantityField).clear();

driver.findElement(quantityField).sendKeys("3");

After changing the quantity, the test should verify that the cart total is updated correctly.


18. Increasing Quantity

Some applications provide a plus button instead of allowing direct editing of the quantity field.

By plusButton =

        By.id("increaseQuantity");

 

driver.findElement(plusButton).click();

The automation should verify that the quantity changed to the expected value.


19. Decreasing Quantity

By minusButton =

        By.id("decreaseQuantity");

 

driver.findElement(minusButton).click();

The test should validate that the quantity decreases correctly and that the total amount is recalculated.


20. Removing a Product

Removing products is another important cart scenario.

By removeButton =

        By.id("removeProduct");

 

driver.findElement(removeButton).click();

After removal, the test can verify that the product is no longer displayed.


21. Verifying Product Removal

boolean productDisplayed =

        driver.findElements(

            By.id("cartProduct")

        ).size() > 0;

 

Assert.assertFalse(productDisplayed);

Using findElements() can be useful when the expected result is that an element should no longer exist.


22. Verifying Product Price

Product price should be validated before and after adding the product to the cart.

String price =

        driver.findElement(

            By.id("productPrice")

        ).getText();

 

Assert.assertEquals(price, "$999");


23. Verifying Cart Total

The total amount should correspond to the application's pricing rules.

String total =

        driver.findElement(

            By.id("cartTotal")

        ).getText();

 

Assert.assertEquals(total, "$999");

For real applications, taxes, discounts, shipping fees, currency formatting, and other business rules may also affect the final total.


24. Price Calculation Validation

For a simple cart containing one product, the expected subtotal can be calculated as:

Expected Subtotal = Product Price × Quantity

Example:

Product Price = $500

Quantity = 2

 

Expected Subtotal = $500 × 2

Expected Subtotal = $1000


25. Validating Multiple Product Totals

For multiple products, the expected subtotal can be calculated as:

Product 1 Total = Price 1 × Quantity 1

Product 2 Total = Price 2 × Quantity 2

Product 3 Total = Price 3 × Quantity 3

 

Expected Subtotal =

Product 1 Total +

Product 2 Total +

Product 3 Total


26. Shopping Cart Assertions

Assertions are used to compare expected application behavior with actual behavior.

Assert.assertEquals(

    actualProduct,

    expectedProduct

);

 

Assert.assertEquals(

    actualPrice,

    expectedPrice

);

 

Assert.assertTrue(

    cartDisplayed

);

 

Assert.assertFalse(

    productRemoved

);


27. Explicit Waits in Shopping Cart Automation

E-commerce applications frequently load products, cart counts, prices, and notifications dynamically. Explicit waits can help synchronize the automation with the application's state.

import java.time.Duration;

import org.openqa.selenium.support.ui.WebDriverWait;

 

WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );


28. Waiting for Add-to-Cart Confirmation

import org.openqa.selenium.support.ui.ExpectedConditions;

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("cartNotification")

    )

);

Explicit waits are generally preferable to arbitrary long sleeps because they allow the test to continue when the required condition is satisfied.


29. Handling Dynamic Cart Elements

Cart rows can be dynamically generated depending on the products selected. Instead of relying only on fixed indexes, automation should use stable attributes and meaningful locators.

By cartItems =

        By.cssSelector(".cart-item");

 

int itemCount =

        driver.findElements(cartItems).size();

 

Assert.assertTrue(itemCount > 0);


30. Searching for a Product

A complete shopping cart test often starts with product search.

By searchBox =

        By.id("search");

 

By searchButton =

        By.id("searchButton");

 

driver.findElement(searchBox)

        .sendKeys("Laptop");

 

driver.findElement(searchButton)

        .click();


31. Verifying Search Results

By searchResults =

        By.cssSelector(".product-item");

 

int results =

        driver.findElements(searchResults).size();

 

Assert.assertTrue(results > 0);


32. Selecting a Product

Once the desired product is found, the automation can open its details.

By productLink =

        By.xpath("//a[contains(text(),'Laptop')]");

 

driver.findElement(productLink).click();


33. End-to-End Shopping Cart Flow

Open Application

        |

        v

Login

        |

        v

Search Product

        |

        v

Select Product

        |

        v

Verify Product Details

        |

        v

Add Product to Cart

        |

        v

Verify Cart Count

        |

        v

Open Cart

        |

        v

Verify Product

        |

        v

Verify Price

        |

        v

Update Quantity

        |

        v

Verify Total

        |

        v

Remove Product

        |

        v

Verify Cart

        |

        v

Add Product Again

        |

        v

Proceed to Checkout

        |

        v

Verify Checkout Page


34. Shopping Cart with Page Object Model

Page Object Model is useful for shopping cart automation because the workflow contains multiple pages and reusable actions. Locators and page-specific operations can be maintained inside their respective classes.

LoginPage

    |

    v

HomePage

    |

    v

ProductPage

    |

    v

CartPage

    |

    v

CheckoutPage

    |

    v

OrderConfirmationPage


35. Login Page Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

            By.id("username");

 

    private By password =

            By.id("password");

 

    private By loginButton =

            By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(

            String user,

            String pass) {

 

        driver.findElement(username)

                .sendKeys(user);

 

        driver.findElement(password)

                .sendKeys(pass);

 

        driver.findElement(loginButton)

                .click();

    }

}


36. Home Page Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class HomePage {

 

    private WebDriver driver;

 

    private By searchBox =

            By.id("search");

 

    private By searchButton =

            By.id("searchButton");

 

    private By cartIcon =

            By.id("cart");

 

    public HomePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void searchProduct(

            String product) {

 

        driver.findElement(searchBox)

                .sendKeys(product);

 

        driver.findElement(searchButton)

                .click();

    }

 

    public void openCart() {

        driver.findElement(cartIcon)

                .click();

    }

}


37. Product Page Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class ProductPage {

 

    private WebDriver driver;

 

    private By productName =

            By.id("productName");

 

    private By productPrice =

            By.id("productPrice");

 

    private By addToCart =

            By.id("addToCart");

 

    public ProductPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public String getProductName() {

        return driver.findElement(

                productName

        ).getText();

    }

 

    public String getProductPrice() {

        return driver.findElement(

                productPrice

        ).getText();

    }

 

    public void addProductToCart() {

        driver.findElement(addToCart)

                .click();

    }

}


38. Cart Page Class with Reusable Methods

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class CartPage {

 

    private WebDriver driver;

 

    private By productName =

            By.cssSelector(".cart-product-name");

 

    private By productPrice =

            By.cssSelector(".cart-product-price");

 

    private By quantity =

            By.cssSelector(".cart-quantity");

 

    private By total =

            By.cssSelector(".cart-total");

 

    private By remove =

            By.cssSelector(".remove-product");

 

    private By checkout =

            By.id("checkout");

 

    public CartPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public String getProductName() {

        return driver.findElement(

                productName

        ).getText();

    }

 

    public String getProductPrice() {

        return driver.findElement(

                productPrice

        ).getText();

    }

 

    public String getQuantity() {

        return driver.findElement(

                quantity

        ).getAttribute("value");

    }

 

    public String getTotal() {

        return driver.findElement(

                total

        ).getText();

    }

 

    public void removeProduct() {

        driver.findElement(remove)

                .click();

    }

 

    public void proceedToCheckout() {

        driver.findElement(checkout)

                .click();

    }

}


39. Complete Shopping Cart Test

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class ShoppingCartTest {

 

    WebDriver driver;

 

    LoginPage loginPage;

    HomePage homePage;

    ProductPage productPage;

    CartPage cartPage;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

                .window()

                .maximize();

 

        driver.get(

            "https://example.com"

        );

 

        loginPage =

                new LoginPage(driver);

 

        homePage =

                new HomePage(driver);

 

        productPage =

                new ProductPage(driver);

 

        cartPage =

                new CartPage(driver);

    }

 

    @Test

    public void addProductToCartTest() {

 

        loginPage.login(

            "testuser",

            "testpassword"

        );

 

        homePage.searchProduct(

            "Laptop"

        );

 

        productPage.addProductToCart();

 

        homePage.openCart();

 

        Assert.assertEquals(

            cartPage.getProductName(),

            "Laptop"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


40. Testing Multiple Products

Multiple products can be handled using a data-driven approach.

@DataProvider(name = "products")

public Object[][] products() {

    return new Object[][] {

        {"Laptop"},

        {"Mobile"},

        {"Headphones"},

        {"Keyboard"}

    };

}

 

@Test(dataProvider = "products")

public void productCartTest(String product) {

 

    homePage.searchProduct(product);

    productPage.addProductToCart();

    homePage.openCart();

 

    Assert.assertTrue(

        cartPage.getProductName()

            .contains(product)

    );

}


41. Shopping Cart Data Provider

Data Providers are useful when the same cart workflow needs to be executed using different products, quantities, prices, or expected values.

@DataProvider(name = "cartData")

public Object[][] cartData() {

    return new Object[][] {

        {"Laptop", 1},

        {"Mobile", 2},

        {"Headphones", 3}

    };

}

 

@Test(dataProvider = "cartData")

public void cartQuantityTest(

        String product,

        int quantity) {

 

    System.out.println(

        product + " - " + quantity

    );

}


42. Positive Shopping Cart Scenarios

  • Add a valid product to the cart.
  • Add multiple valid products.
  • Update quantity with a valid value.
  • Remove an existing product.
  • Apply a valid coupon.
  • Proceed to checkout with valid cart data.
  • Verify correct product information.
  • Verify correct price and total.


43. Negative Shopping Cart Scenarios

  • Attempt to add an unavailable product.
  • Enter an invalid quantity.
  • Enter zero quantity if the application does not permit it.
  • Enter an invalid negative quantity.
  • Apply an expired coupon.
  • Apply an invalid coupon.
  • Proceed to checkout with an empty cart.
  • Attempt checkout with invalid information.


44. Empty Cart Validation

The automation should verify the behavior of an empty cart.

By emptyCartMessage =

        By.id("emptyCartMessage");

 

String message =

        driver.findElement(

            emptyCartMessage

        ).getText();

 

Assert.assertEquals(

    message,

    "Your cart is empty"

);


45. Coupon Code Testing

Many e-commerce applications support discount or coupon codes.

By couponField =

        By.id("coupon");

 

By applyCoupon =

        By.id("applyCoupon");

 

driver.findElement(couponField)

        .sendKeys("SAVE10");

 

driver.findElement(applyCoupon)

        .click();


46. Valid Coupon Validation

By discountAmount =

        By.id("discount");

 

String discount =

        driver.findElement(

            discountAmount

        ).getText();

 

Assert.assertTrue(

    discount.contains("10")

);


47. Invalid Coupon Validation

driver.findElement(couponField)

        .sendKeys("INVALID");

 

driver.findElement(applyCoupon)

        .click();

 

By errorMessage =

        By.id("couponError");

 

Assert.assertTrue(

    driver.findElement(errorMessage)

        .isDisplayed()

);


48. Verifying Cart Persistence

A useful test is verifying whether the cart remains populated after navigating to another page or refreshing the browser.

driver.navigate().refresh();

 

String product =

        cartPage.getProductName();

 

Assert.assertEquals(

    product,

    "Laptop"

);


49. Browser Refresh and Cart Validation

Depending on the application's architecture, cart information may be stored in a server-side session, local storage, cookies, or another mechanism. The automation should verify the behavior required by the application specification.


50. Handling Alerts in Cart Automation

Some applications display browser alerts or confirmation dialogs when removing products or performing important actions.

import org.openqa.selenium.Alert;

 

Alert alert =

        driver.switchTo().alert();

 

String message =

        alert.getText();

 

alert.accept();


51. Handling Dynamic Elements

Shopping carts can contain dynamically generated product rows. XPath or CSS selectors can be constructed using stable attributes when appropriate.

By product =

        By.xpath(

            "//div[contains(@class,'cart-item')]" +

            "[.//span[contains(text(),'Laptop')]]"

        );

 

driver.findElement(product)

        .click();


52. Handling Stale Elements

Cart updates can refresh or replace DOM elements. If a previously located element becomes invalid after a cart update, Selenium may throw a StaleElementReferenceException.

A practical approach is to locate the element again after the DOM-changing operation.

driver.findElement(

    By.id("increaseQuantity")

).click();

 

String total =

    driver.findElement(

        By.id("cartTotal")

    ).getText();


53. Handling NoSuchElementException

If a locator does not identify an element, Selenium can throw a NoSuchElementException. Use stable locators and appropriate waits, and verify that the element should exist in the current application state.


54. Shopping Cart Test Case Design

Test CaseActionExpected Result
TC01Add productProduct appears in cart.
TC02Add multiple productsAll products appear.
TC03Increase quantityQuantity and total update.
TC04Decrease quantityQuantity and total decrease.
TC05Remove productProduct disappears.
TC06Verify priceCorrect product price displayed.
TC07Verify totalCorrect total displayed.
TC08Apply couponDiscount is calculated correctly.
TC09Open empty cartEmpty-cart message displayed.
TC10Proceed to checkoutCheckout page opens.


55. Shopping Cart with TestNG

TestNG can be used to organize cart tests using annotations such as @BeforeMethod, @Test, and @AfterMethod.

@BeforeMethod

public void setup() {

    driver = new ChromeDriver();

}

 

@Test

public void addToCartTest() {

    System.out.println("Add to cart test");

}

 

@AfterMethod

public void tearDown() {

    if (driver != null) {

        driver.quit();

    }

}


56. Shopping Cart with TestNG Groups

Large test suites can organize tests into groups such as smoke, regression, cart, checkout, and negative tests.

@Test(groups = {"cart", "smoke"})

public void addProductTest() {

    System.out.println("Add product");

}

 

@Test(groups = {"cart", "regression"})

public void removeProductTest() {

    System.out.println("Remove product");

}


57. Shopping Cart Screenshots

Screenshots are useful when a cart test fails because they provide visual information about the browser state at the time of failure.

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import java.io.File;

 

File screenshot =

        ((TakesScreenshot) driver)

        .getScreenshotAs(

            OutputType.FILE

        );

In a production framework, the screenshot can be saved using an appropriate file utility and attached to the test report.


58. Shopping Cart Test Reporting

Test reports can show which shopping cart scenarios passed, failed, or were skipped.

Shopping Cart Test Suite

        |

        +-- Add Product       PASS

        |

        +-- Verify Product    PASS

        |

        +-- Update Quantity   PASS

        |

        +-- Verify Total      PASS

        |

        +-- Remove Product    FAIL

        |

        +-- Checkout          SKIP


59. Complete End-to-End Shopping Cart Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class ShoppingCartTest {

 

    private WebDriver driver;

 

    private LoginPage loginPage;

    private HomePage homePage;

    private ProductPage productPage;

    private CartPage cartPage;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

                .window()

                .maximize();

 

        driver.get(

            "https://example.com"

        );

 

        loginPage =

                new LoginPage(driver);

 

        homePage =

                new HomePage(driver);

 

        productPage =

                new ProductPage(driver);

 

        cartPage =

                new CartPage(driver);

    }

 

    @Test

    public void completeShoppingCartFlow() {

 

        loginPage.login(

            "testuser",

            "testpassword"

        );

 

        homePage.searchProduct(

            "Laptop"

        );

 

        String product =

                productPage.getProductName();

 

        Assert.assertEquals(

            product,

            "Laptop"

        );

 

        productPage.addProductToCart();

 

        homePage.openCart();

 

        Assert.assertEquals(

            cartPage.getProductName(),

            "Laptop"

        );

 

        String price =

                cartPage.getProductPrice();

 

        Assert.assertNotNull(price);

 

        cartPage.updateQuantity("2");

 

        String total =

                cartPage.getTotal();

 

        Assert.assertNotNull(total);

 

        cartPage.proceedToCheckout();

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


60. Real-World E-Commerce Shopping Flow

User

 |

 v

Login

 |

 v

Home Page

 |

 v

Search Product

 |

 v

Product Listing

 |

 v

Product Details

 |

 v

Add to Cart

 |

 v

Shopping Cart

 |

 +---- Verify Product

 |

 +---- Verify Price

 |

 +---- Update Quantity

 |

 +---- Apply Coupon

 |

 +---- Verify Total

 |

 +---- Remove Product

 |

 v

Checkout

 |

 v

Address

 |

 v

Payment

 |

 v

Order Confirmation


61. Practical Project Structure

src

|-- main

|   |-- java

|       |-- pages

|       |   |-- LoginPage.java

|       |   |-- HomePage.java

|       |   |-- ProductPage.java

|       |   |-- CartPage.java

|       |   |-- CheckoutPage.java

|       |   |-- OrderConfirmationPage.java

|       |

|       |-- utilities

|           |-- DriverFactory.java

|           |-- ConfigReader.java

|           |-- ScreenshotUtility.java

|

|-- test

|   |-- java

|       |-- tests

|           |-- LoginTest.java

|           |-- ProductTest.java

|           |-- ShoppingCartTest.java

|           |-- CheckoutTest.java

|

|-- testng.xml

|-- pom.xml


62. Driver Factory for Shopping Cart Automation

A Driver Factory can centralize browser creation so that individual test classes do not need to duplicate browser initialization code.

public class DriverFactory {

 

    public static WebDriver createDriver(

            String browser) {

 

        if (browser.equalsIgnoreCase("chrome")) {

            return new ChromeDriver();

        }

 

        if (browser.equalsIgnoreCase("firefox")) {

            return new FirefoxDriver();

        }

 

        if (browser.equalsIgnoreCase("edge")) {

            return new EdgeDriver();

        }

 

        throw new IllegalArgumentException(

            "Unsupported browser: " + browser

        );

    }

}


63. Cross-Browser Shopping Cart Testing

The same shopping cart workflow can be executed against different browsers.

Chrome

   |

   +-- Shopping Cart Test

   |

Firefox

   |

   +-- Shopping Cart Test

   |

Edge

   |

   +-- Shopping Cart Test

This helps identify browser-specific UI or interaction issues.


64. Shopping Cart with Maven

Maven can be used to manage Selenium, TestNG, reporting, and other project dependencies.

mvn clean test

A Maven project can also be integrated into CI/CD systems for automated regression execution.


65. Shopping Cart Automation in CI/CD

Developer Commit

        |

        v

CI/CD Pipeline

        |

        v

Maven Build

        |

        v

TestNG

        |

        v

Shopping Cart Tests

        |

        v

Selenium WebDriver

        |

        v

Browser

        |

        v

Application

        |

        v

Assertions

        |

        v

Test Report


66. Common Mistakes in Shopping Cart Automation

  • Using unstable XPath locators.
  • Using excessive Thread.sleep() statements.
  • Not waiting for dynamically loaded cart elements.
  • Not validating the result after clicking Add to Cart.
  • Sharing one WebDriver instance unsafely between parallel tests.
  • Hard-coding sensitive credentials.
  • Putting all Selenium logic inside test classes.
  • Not validating product price and total.
  • Ignoring negative quantity scenarios.
  • Not handling stale elements after cart updates.
  • Not capturing useful failure information.
  • Creating duplicate page locators in multiple test classes.


67. Best Practices for Shopping Cart Automation

  • Use Page Object Model for page-specific actions.
  • Use stable locators based on reliable application attributes.
  • Prefer explicit waits for dynamic application behavior.
  • Keep test logic separate from page interaction logic.
  • Use TestNG assertions for validations.
  • Use Data Providers for multiple product and quantity combinations.
  • Use reusable utility methods for screenshots and common operations.
  • Keep WebDriver lifecycle management centralized.
  • Use independent test data for parallel execution.
  • Avoid hard-coded secrets.
  • Generate reports for every execution.
  • Capture screenshots when important tests fail.
  • Keep test cases focused on business behavior.
  • Run cart tests as part of regression suites.


68. Shopping Cart Automation Checklist

CheckStatus to Validate
Application opensPage loads successfully.
LoginUser reaches application.
Product searchExpected product is displayed.
Product detailsName and price are correct.
Add to cartProduct is added.
Cart countCount is updated.
Cart productExpected product appears.
QuantityCorrect quantity is displayed.
PriceCorrect price is displayed.
SubtotalSubtotal is correct.
DiscountDiscount is calculated correctly.
TotalTotal is correct.
Remove productProduct is removed.
CheckoutCheckout page opens correctly.
ReportExecution result is recorded.


69. Shopping Cart Automation Interview Questions

1. What is shopping cart automation?

Shopping cart automation is the automated validation of e-commerce cart workflows using tools such as Selenium WebDriver.

2. Which Selenium operations are commonly used?

Common operations include click, sendKeys, clear, getText, getAttribute, isDisplayed, findElement, findElements, and navigation methods.

3. What scenarios should be tested in a shopping cart?

Important scenarios include adding products, updating quantities, removing products, validating prices, calculating totals, applying coupons, and proceeding to checkout.

4. Why is Page Object Model useful for shopping cart automation?

POM separates page-specific locators and actions from test cases and makes the framework easier to maintain and reuse.

5. How can multiple products be tested?

Multiple products can be supplied through a TestNG Data Provider or another external test-data source.

6. How do you verify that a product was added?

Navigate to the cart and verify the product name, quantity, price, or another application-specific identifier.

7. How do you validate cart totals?

Calculate the expected amount according to the application's pricing rules and compare it with the displayed cart total.

8. How do you handle dynamic cart elements?

Use stable locators and appropriate explicit waits, and locate elements again after DOM-changing operations when necessary.

9. Why should Thread.sleep() be avoided where possible?

Fixed delays can unnecessarily slow tests and may still fail when the application takes longer than the selected delay. Explicit waits can synchronize against actual conditions.

10. How can screenshots help?

Screenshots provide visual evidence of the browser state when a test fails and can be attached to reports.

11. How can shopping cart tests run on multiple browsers?

A Driver Factory or parameterized browser configuration can create the required WebDriver implementation for Chrome, Firefox, Edge, or other supported browsers.

12. What is a stale element in cart automation?

A stale element occurs when a previously located DOM element is no longer attached to the current page DOM, commonly after a cart update or page refresh.

13. How can cart tests be integrated into CI/CD?

The Maven/TestNG automation suite can be executed from a CI/CD pipeline and its reports can be published as build artifacts.

14. What is the benefit of Data Providers in shopping cart testing?

They allow the same test logic to run with different products, quantities, expected prices, or other data combinations.

15. What should not be hard-coded in automation tests?

Credentials, API keys, tokens, and other sensitive information should generally be managed through appropriate secure configuration mechanisms.


70. Quick Reference Table

ConceptPurpose
WebDriverControls the browser.
ByDefines element locators.
ClickPerforms actions such as Add to Cart.
sendKeys()Enters product or quantity data.
clear()Clears editable fields.
getText()Reads visible product, price, and message text.
findElements()Finds multiple elements and can help validate collections.
WebDriverWaitSynchronizes with dynamic application conditions.
AssertValidates expected versus actual results.
DataProviderSupplies multiple test-data combinations.
POMSeparates page actions and locators from tests.
TestNGOrganizes and executes tests.
MavenBuild and dependency management.


71. Practical Exercises

  1. Create a test that adds one product to the cart.
  2. Verify the product name after adding it.
  3. Verify the product price.
  4. Verify the cart count.
  5. Add three different products.
  6. Verify all three products in the cart.
  7. Increase the quantity of one product.
  8. Verify the updated subtotal.
  9. Decrease the quantity.
  10. Remove one product.
  11. Verify that the removed product no longer exists.
  12. Test an empty cart.
  13. Apply a valid coupon.
  14. Apply an invalid coupon.
  15. Proceed from cart to checkout.
  16. Create a Page Object Model for the complete flow.
  17. Use a Data Provider for multiple products.
  18. Add screenshot capture for failed tests.
  19. Generate a TestNG or external report.
  20. Execute the complete suite using Maven.


72. Complete Learning Roadmap

  1. Understand Selenium WebDriver basics.
  2. Learn Selenium locators.
  3. Learn browser navigation.
  4. Learn element interactions.
  5. Understand explicit waits.
  6. Learn TestNG.
  7. Learn assertions.
  8. Understand Page Object Model.
  9. Create LoginPage and HomePage classes.
  10. Create ProductPage and CartPage classes.
  11. Automate Add to Cart.
  12. Automate quantity changes.
  13. Automate product removal.
  14. Validate prices and totals.
  15. Automate coupon scenarios.
  16. Automate checkout.
  17. Add Data Providers.
  18. Add screenshots.
  19. Add test reports.
  20. Run tests through Maven.
  21. Integrate tests with CI/CD.
  22. Build a complete reusable e-commerce automation framework.


73. Summary

Shopping Cart Automation is an important real-world Selenium automation project for validating e-commerce workflows. It covers product search, product selection, Add to Cart, cart count, quantity updates, price verification, total calculation, product removal, coupon handling, and checkout navigation.

A maintainable implementation can use Selenium WebDriver for browser automation, TestNG for test execution and assertions, Page Object Model for reusable page classes, Data Providers for multiple test-data combinations, and Maven for build and dependency management.

The overall automation flow can be represented as:

Test Data

    |

    v

TestNG

    |

    v

Page Objects

    |

    v

Selenium WebDriver

    |

    v

E-Commerce Application

    |

    v

Cart Validation

    |

    v

Assertions

    |

    v

Screenshots / Reports

    |

    v

CI/CD

Final Takeaway: A well-designed shopping cart automation framework should validate the complete customer journey while keeping test cases readable, page interactions reusable, synchronization reliable, test data manageable, and failures easy to diagnose.


74. Course Resources

whatsapp