QA and Test Automation · Lab 15 of 35
Selenium 4 Java With Page Objects: ShopRung Hands-On Lab
Build a Selenium 4 suite in Java the way SDET teams do: a base test with a fresh headless Chrome per test and a screenshot on failure, three page objects with stable CSS locators and explicit waits, API login through localStorage, and six tests from login to a placed order.
⏱ 75 minIntermediate💸 Free7 steps
Java 21Maven 3.9JUnit 5.11Selenium 4.27 (Selenium Manager)Google ChromeShopRung
Overview video
What you will build
A Maven project that drives ShopRung in Chrome with Selenium WebDriver, with 6 tests in three classes:
BaseTest: resets ShopRung, starts a fresh (headless) Chrome for every test, saves a screenshot when a test fails, always quits the browser, and can log a user in through the API by writing ShopRung's session into localStorage.LoginPage,ProductsPage,CartPage: page objects that own every locator and every wait, with methods named after what a user does.LoginTest(a real login, and the generic error for a wrong password),SearchTest(the mug search, the disabled out of stock button) andCheckoutTest(SAVE10 at exactly $50.00 for $49.99, and an order for $29.98).
Before you start
- Your first Java test project: JDK 21 and Maven.
- The episodes this lab puts into practice: Selenium 4 with Java, Page Object Model, DOM and locators and Waits and synchronization.
- ShopRung installed, as in lab 1 setup, and Google Chrome installed.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Check Java, Maven and Chrome
You do not need to download chromedriver: Selenium Manager, built into Selenium 4, finds your Chrome and downloads the matching driver the first time a test runs.
java -version
mvn -v openjdk version "21.0.x" ... Apache Maven 3.9.x ...
S3Make the project folders
Tests in dev.algorung.ui, page objects in dev.algorung.ui.pages.
mkdir -p shoprung-selenium/src/test/java/dev/algorung/ui/pages
cd shoprung-seleniummkdir -p shoprung-selenium/src/test/java/dev/algorung/ui/pages
cd shoprung-seleniummkdir shoprung-selenium\src\test\java\dev\algorung\ui\pages
cd shoprung-selenium The pom.xml and an API helper
JUnit 5 and Selenium at pinned versions, and a small class that talks to ShopRung's API.
Create pom.xml. selenium-java brings WebDriver, the Chrome driver support and Selenium Manager.
Then create Shop.java. UI tests should use the UI only for what they test; setup goes through the API, which is faster and more reliable. This helper resets ShopRung and logs a user in, using the JDK's own HTTP client.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>dev.algorung</groupId>
<artifactId>shoprung-selenium</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.11.4</junit.version>
<selenium.version>4.27.0</selenium.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
</project> - WebDriver, browser drivers support and Selenium Manager in one dependency.line 26
package dev.algorung.ui;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/** API helpers for UI tests: reset the data, and log in without the login page. */
public final class Shop {
public static final String BASE_URL = System.getProperty("baseUrl", "http://localhost:8080");
private static final HttpClient HTTP = HttpClient.newHttpClient();
private Shop() {}
public static void reset() {
post("/api/test/reset", "");
}
/** The raw login response: {"token": "...", "expiresIn": 7200, "user": {...}}. */
public static String login(String email, String password) {
return post("/api/auth/login", "{\"email\":\"" + email + "\",\"password\":\"" + password + "\"}");
}
private static String post(String path, String json) {
try {
HttpRequest request = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) throw new IllegalStateException(path + ": HTTP " + response.statusCode());
return response.body();
} catch (java.io.IOException | InterruptedException e) {
throw new IllegalStateException("ShopRung is not reachable at " + BASE_URL + ". Start it with: npm start", e);
}
}
} mvn test -DbaseUrl=...for another server.line 10- Returns the token and the user, for logging in without the form.line 20
The base test: a browser per test, a screenshot on failure
BaseTest gives every test fresh data, a fresh Chrome, an explicit wait, and evidence when it fails.
Create BaseTest.java. Every test class extends it:
@BeforeEachresets ShopRung and starts a new Chrome. Headless by default (no window, like CI); run with-Dheaded=trueto watch. One browser per test means no cookies or carts leak between tests.WebDriverWaitwith 10 seconds is the explicit wait the page objects use. There is no implicit wait and noThread.sleepanywhere in this project.- The
@RegisterExtensionfield runs right after each test method, before@AfterEach, while the browser is still open. If the test failed, it saves a screenshot totarget/screenshots/. @AfterEachcallsquit(), neverclose(), so no browser or driver process is left behind.loginAslogs in through the API, then writes the token and user intolocalStorage, exactly where ShopRung's page keeps its session, and refreshes. Tests that are not about logging in skip the form.
package dev.algorung.ui;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
/** Every UI test: fresh data, a fresh browser, a screenshot if it fails, and the browser closed afterwards. */
public abstract class BaseTest {
protected WebDriver driver;
protected WebDriverWait wait;
@BeforeEach
void startBrowser() {
Shop.reset();
ChromeOptions options = new ChromeOptions();
if (!Boolean.getBoolean("headed")) options.addArguments("--headless=new"); // -Dheaded=true to watch
options.addArguments("--window-size=1280,800");
driver = new ChromeDriver(options); // Selenium Manager finds or downloads chromedriver
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
/** Runs right after the test method, before @AfterEach: the browser is still open. */
@RegisterExtension
AfterTestExecutionCallback screenshotOnFailure = context -> {
if (context.getExecutionException().isPresent() && driver != null) {
Path dir = Path.of("target", "screenshots");
Files.createDirectories(dir);
Path shot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).toPath();
Files.copy(shot, dir.resolve(context.getDisplayName().replaceAll("[^A-Za-z0-9]", "_") + ".png"),
StandardCopyOption.REPLACE_EXISTING);
}
};
@AfterEach
void quitBrowser() {
if (driver != null) driver.quit(); // quit, not close: ends the browser and the driver process
}
/** Logs in through the API and puts the session where ShopRung's page keeps it, skipping the login form. */
protected void loginAs(String email, String password) {
String body = Shop.login(email, password);
String token = body.replaceAll(".*\"token\":\"([^\"]+)\".*", "$1");
String user = body.replaceAll(".*\"user\":(\\{[^}]*\\}).*", "$1");
driver.get(Shop.BASE_URL + "/");
((JavascriptExecutor) driver).executeScript(
"localStorage.setItem('shoprung.token', arguments[0]);"
+ "localStorage.setItem('shoprung.user', arguments[1]);", token, user);
driver.navigate().refresh();
}
} - Chrome's current headless mode.
-Dheaded=trueshows the window.line 28 - Selenium Manager resolves chromedriver for your Chrome version.line 30
- Evidence for every failure, saved before the browser closes.line 36
quitends the browser and the driver;closeonly closes a window.line 48- The same keys ShopRung's own login writes.line 58
Stuck on this step?
SessionNotCreatedExceptionor "Unable to obtain driver".- Selenium Manager could not find Chrome or download the driver. Install Chrome, check your network or proxy, and run again.
The login page object and two login tests
LoginPage owns the login locators and waits; two tests check a valid and a wrong login.
Create pages/LoginPage.java. Each locator is a By constant at the top: by name for the inputs, CSS on the form's test id for the button, and the role="alert" element for errors. Methods are named after what a user does. logIn returns a ProductsPage, because that is where a successful login lands, so tests can chain.
Note the wait in open(): ShopRung draws the form with JavaScript after the page loads, so the page object waits until the email field is visible before anyone types. Waits live inside page objects, not in tests.
Then create pages/ProductsPage.java (the first version below; you will extend it in step 5) and LoginTest.java. A wrong password must show Email or password is wrong, the same message as for an unknown email.
package dev.algorung.ui.pages;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
import dev.algorung.ui.Shop;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
/** The login page: #/login. */
public class LoginPage {
private static final By EMAIL = By.name("email");
private static final By PASSWORD = By.name("password");
private static final By SUBMIT = By.cssSelector("[data-testid=login-form] button[type=submit]");
private static final By ALERT = By.cssSelector("[role=alert]");
private final WebDriver driver;
private final WebDriverWait wait;
public LoginPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public LoginPage open() {
driver.get(Shop.BASE_URL + "/#/login");
wait.until(visibilityOfElementLocated(EMAIL)); // the form is drawn by JavaScript
return this;
}
/** Fills the form and submits. Returns the products page, where a successful login lands. */
public ProductsPage logIn(String email, String password) {
driver.findElement(EMAIL).sendKeys(email);
driver.findElement(PASSWORD).sendKeys(password);
driver.findElement(SUBMIT).click();
return new ProductsPage(driver, wait);
}
/** The error message shown to the user (role="alert", so screen readers announce it too). */
public String alertText() {
return wait.until(visibilityOfElementLocated(ALERT)).getText();
}
} - Locators live here once. A UI change means one edit.line 12
- Wait for the JavaScript-drawn form.line 27
- Returns the next page: a fluent, readable test.line 32
package dev.algorung.ui.pages;
import static org.openqa.selenium.support.ui.ExpectedConditions.textToBe;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
import dev.algorung.ui.Shop;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
/** The product list and the header around it: search, cards, the cart badge and the user's name. */
public class ProductsPage {
private static final By SEARCH = By.id("q");
private static final By SEARCH_BUTTON = By.cssSelector("form[role=search] button[type=submit]");
private static final By RESULT_COUNT = By.cssSelector("[data-testid=result-count]");
private static final By USER_NAME = By.cssSelector("[data-testid=user-name]");
private final WebDriver driver;
private final WebDriverWait wait;
public ProductsPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public ProductsPage open() {
driver.get(Shop.BASE_URL + "/");
wait.until(visibilityOfElementLocated(RESULT_COUNT));
return this;
}
/** Searches, then waits until the count shows the expected text: the page re-renders after the API answers. */
public ProductsPage searchFor(String term, String expectedCount) {
driver.findElement(SEARCH).sendKeys(term);
driver.findElement(SEARCH_BUTTON).click();
wait.until(textToBe(RESULT_COUNT, expectedCount));
return this;
}
public String resultCount() {
return driver.findElement(RESULT_COUNT).getText();
}
/** One product card, found by its SKU: a stable attribute, unlike its position in the grid. */
public WebElement card(String sku) {
return driver.findElement(By.cssSelector("[data-testid=product-card][data-sku='" + sku + "']"));
}
public boolean canAdd(String sku) {
return card(sku).findElement(By.cssSelector("button[data-add]")).isEnabled();
}
public String userName() {
return wait.until(visibilityOfElementLocated(USER_NAME)).getText();
}
} - Used in the next step.line 34
package dev.algorung.ui;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.algorung.ui.pages.LoginPage;
import org.junit.jupiter.api.Test;
class LoginTest extends BaseTest {
@Test
void aValidLoginShowsTheUsersName() {
var products = new LoginPage(driver, wait).open().logIn("alice@shoprung.test", "Alice123!");
assertEquals("Hi, Alice Shah", products.userName());
}
@Test
void aWrongPasswordShowsAGenericError() {
var login = new LoginPage(driver, wait).open();
login.logIn("alice@shoprung.test", "wrong");
assertEquals("Email or password is wrong", login.alertText());
}
} - The generic message: no hint whether the email exists.line 19
mvn test -Dtest=LoginTest [INFO] Running dev.algorung.ui.LoginTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Search: stable locators and waits for the result
Two search tests that find cards by SKU and wait for the page to re-render.
Look at ProductsPage again. Two choices make these tests stable:
- Cards by SKU, not position.
card("MG-202")uses the card'sdata-skuattribute. "The fourth card" would break the day the products are sorted differently. - Wait for the result, not for time. After clicking Search, the old results stay on screen until the API answers.
searchForwaits until the count shows the expected text, usingtextToBe. Reading the count straight after the click would read the old value.
Create SearchTest.java. The mug search must show 2 products with the Green Build Mug, and the Red Build Mug says Out of stock with a disabled button.
package dev.algorung.ui;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.algorung.ui.pages.ProductsPage;
import org.junit.jupiter.api.Test;
class SearchTest extends BaseTest {
@Test
void searchFindsTheTwoMugs() {
var products = new ProductsPage(driver, wait).open().searchFor("mug", "2 products");
assertTrue(products.card("MG-201").getText().contains("Green Build Mug"));
}
@Test
void theOutOfStockMugCannotBeAdded() {
var products = new ProductsPage(driver, wait).open().searchFor("mug", "2 products");
assertTrue(products.card("MG-202").getText().contains("Out of stock"));
assertFalse(products.canAdd("MG-202"));
}
} - The page object waits for this exact count.line 12
- CART rule: out of stock cannot be added.line 20
mvn test -Dtest=SearchTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
The cart page object, and a fluent product page
CartPage for quantities, coupons, totals and placing an order; ProductsPage can add to cart and open the cart.
Replace pages/ProductsPage.java with the full version: addToCart clicks a product's button by its accessible name and waits for the cart badge to change (the add is a request to the server), and openCart returns a CartPage.
Create pages/CartPage.java. Its methods also wait for their own results: setQuantity types the number, presses Tab (the cart saves a quantity when the field loses focus) and waits for the new subtotal; applyCoupon waits for the coupon message; placeOrder waits for the order page to say PLACED. Tests never wait themselves.
package dev.algorung.ui.pages;
import static org.openqa.selenium.support.ui.ExpectedConditions.textToBe;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
import dev.algorung.ui.Shop;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
/** The product list and the header around it: search, cards, the cart badge and the user's name. */
public class ProductsPage {
private static final By SEARCH = By.id("q");
private static final By SEARCH_BUTTON = By.cssSelector("form[role=search] button[type=submit]");
private static final By RESULT_COUNT = By.cssSelector("[data-testid=result-count]");
private static final By CART_COUNT = By.cssSelector("[data-testid=cart-count]");
private static final By USER_NAME = By.cssSelector("[data-testid=user-name]");
private final WebDriver driver;
private final WebDriverWait wait;
public ProductsPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public ProductsPage open() {
driver.get(Shop.BASE_URL + "/");
wait.until(visibilityOfElementLocated(RESULT_COUNT));
return this;
}
/** Searches, then waits until the count shows the expected text: the page re-renders after the API answers. */
public ProductsPage searchFor(String term, String expectedCount) {
driver.findElement(SEARCH).sendKeys(term);
driver.findElement(SEARCH_BUTTON).click();
wait.until(textToBe(RESULT_COUNT, expectedCount));
return this;
}
public String resultCount() {
return driver.findElement(RESULT_COUNT).getText();
}
/** One product card, found by its SKU: a stable attribute, unlike its position in the grid. */
public WebElement card(String sku) {
return driver.findElement(By.cssSelector("[data-testid=product-card][data-sku='" + sku + "']"));
}
public boolean canAdd(String sku) {
return card(sku).findElement(By.cssSelector("button[data-add]")).isEnabled();
}
/** Clicks a product's Add to cart button and waits for the badge to show the new count. */
public ProductsPage addToCart(String productName, String expectedBadge) {
driver.findElement(By.cssSelector("button[aria-label='Add " + productName + " to cart']")).click();
wait.until(textToBe(CART_COUNT, expectedBadge));
return this;
}
public String userName() {
return wait.until(visibilityOfElementLocated(USER_NAME)).getText();
}
public CartPage openCart() {
return new CartPage(driver, wait).open();
}
} - Each Add button's accessible name includes its product.line 57
- Wait for the server's answer before moving on.line 58
package dev.algorung.ui.pages;
import static org.openqa.selenium.support.ui.ExpectedConditions.textToBe;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
import dev.algorung.ui.Shop;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
/** The cart (#/cart) and, after Place order, the order page it leads to. */
public class CartPage {
private static final By COUPON = By.id("coupon");
private static final By APPLY = By.cssSelector("[data-testid=coupon-form] button[type=submit]");
private static final By COUPON_MESSAGE = By.cssSelector("[data-testid=coupon-message]");
private static final By SUBTOTAL = By.cssSelector("[data-testid=subtotal]");
private static final By DISCOUNT = By.cssSelector("[data-testid=discount]");
private static final By SHIPPING = By.cssSelector("[data-testid=shipping]");
private static final By TOTAL = By.cssSelector("[data-testid=total]");
private static final By CHECKOUT = By.cssSelector("[data-testid=checkout]");
private static final By ORDER_STATUS = By.cssSelector("[data-testid=order-status]");
private final WebDriver driver;
private final WebDriverWait wait;
public CartPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public CartPage open() {
driver.get(Shop.BASE_URL + "/#/cart");
wait.until(visibilityOfElementLocated(TOTAL));
return this;
}
/** Types a new quantity; Tab leaves the field, which saves it. Waits for the new subtotal. */
public CartPage setQuantity(int productId, int quantity, String expectedSubtotal) {
WebElement field = driver.findElement(By.id("q" + productId));
field.clear();
field.sendKeys(String.valueOf(quantity), Keys.TAB);
wait.until(textToBe(SUBTOTAL, expectedSubtotal));
return this;
}
public CartPage applyCoupon(String code) {
driver.findElement(COUPON).sendKeys(code);
driver.findElement(APPLY).click();
wait.until(visibilityOfElementLocated(COUPON_MESSAGE));
return this;
}
public String couponMessage() { return driver.findElement(COUPON_MESSAGE).getText(); }
public String subtotal() { return driver.findElement(SUBTOTAL).getText(); }
public String discount() { return driver.findElement(DISCOUNT).getText(); }
public String shipping() { return driver.findElement(SHIPPING).getText(); }
public String total() { return driver.findElement(TOTAL).getText(); }
/** Places the order and waits for the order page. */
public CartPage placeOrder() {
driver.findElement(CHECKOUT).click();
wait.until(textToBe(ORDER_STATUS, "PLACED"));
return this;
}
public String orderMessage() {
return driver.findElement(By.cssSelector("[data-testid=order-placed]")).getText();
}
public String orderTotal() {
return driver.findElement(By.cssSelector("[data-testid=order-total]")).getText();
}
} - Each quantity field's id is q plus the product id.line 41
- Leaving the field fires the change that saves the quantity.line 43
- Wait for the order page before reading it.line 64
Checkout tests, logged in through the API
SAVE10 at exactly $50.00, and a placed order, without touching the login form.
Create CheckoutTest.java. Its @BeforeEach calls loginAs, so the browser starts logged in as Alice. JUnit runs the base class's @BeforeEach first, so the browser exists by then.
The SAVE10 test reads like the user's journey: open the products, add the notebook, open the cart, set the quantity to 4 ($50.00), apply save10. assertAll then checks all four numbers the shopper sees and reports every mismatch: Coupon applied, -$5.00, $4.99, $49.99. The order test adds the Testing Field Guide and places the order: Thank you! Your order is placed. and $29.98.
package dev.algorung.ui;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import dev.algorung.ui.pages.CartPage;
import dev.algorung.ui.pages.ProductsPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class CheckoutTest extends BaseTest {
@BeforeEach
void logInThroughTheApi() {
loginAs("alice@shoprung.test", "Alice123!"); // no login form: that is LoginTest's job
}
@Test
void save10AtExactly50DollarsGivesATotalOf49_99() {
CartPage cart = new ProductsPage(driver, wait).open()
.addToCart("Clean Code Notebook", "1")
.openCart()
.setQuantity(1, 4, "$50.00")
.applyCoupon("save10");
assertAll(
() -> assertEquals("Coupon applied", cart.couponMessage()),
() -> assertEquals("-$5.00", cart.discount()),
() -> assertEquals("$4.99", cart.shipping()),
() -> assertEquals("$49.99", cart.total()));
}
@Test
void placingAnOrderShowsItAsPlaced() {
CartPage order = new ProductsPage(driver, wait).open()
.addToCart("Testing Field Guide", "1")
.openCart()
.placeOrder();
assertEquals("Thank you! Your order is placed.", order.orderMessage());
assertEquals("$29.98", order.orderTotal());
}
} - Setup through the API; LoginTest covers the form.line 14
- 4 × $12.50: exactly the SAVE10 minimum.line 22
- All four numbers checked, all mismatches reported.line 24
mvn test [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.ui.CheckoutTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.ui.LoginTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.ui.SearchTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Watch it, and run it like CI
A headed run to see the browser, and the reports CI reads.
-Dheaded=true opens a visible Chrome for each test, which is the quickest way to understand a failure. In CI, tests run headless, Surefire writes JUnit XML to target/surefire-reports/, and target/screenshots/ should be uploaded as an artifact so failures can be seen. To run on many browsers or machines, the same tests connect to a Selenium Grid with RemoteWebDriver (parallel and cross-browser).
mvn test -Dtest=CheckoutTest -Dheaded=true Chrome opens twice, adds products and places an order. [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
Check it works
Switch on ShopRung's coupon-boundary bug and run the suite. Only the SAVE10 test fails: ShopRung refuses the coupon at $50.00, so the coupon message never appears and the page object's wait times out. Open target/screenshots/: the screenshot shows the cart with the shop's error.
Then try search-case (both search tests fail) and slow-search (everything still passes: the explicit waits give the slow search time). Turn the bugs off at the end.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
mvn test [ERROR] CheckoutTest.save10AtExactly50DollarsGivesATotalOf49_99 » Timeout Expected condition failed: waiting for visibility of element located by By.cssSelector: [data-testid=coupon-message] ... [ERROR] Tests run: 6, Failures: 0, Errors: 1, Skipped: 0 ls target/screenshots save10AtExactly50DollarsGivesATotalOf49_99__.png
Troubleshooting
NoSuchElementException right after opening a page.
ShopRung draws pages with JavaScript. Wait in the page object's open() for an element of that page before using it.
A test reads an old value (for example "12 products").
It read before the page re-rendered. Wait for the expected state with textToBe instead of reading straight after the click.
StaleElementReferenceException.
The page re-rendered and the stored element is gone. Find elements again through the page object instead of keeping WebElement references across actions.
Checkout tests start logged out.
loginAs must open the site before writing localStorage (localStorage belongs to the site), then refresh so ShopRung reads it.
Chrome processes pile up on your machine.
A test path skipped quit(). Keep it in @AfterEach, which runs even when the test fails.
What changes in production
- Teams keep page objects in their own package (often per feature), with components such as the header shared between pages.
- Setup and logins go through the API; only a few tests drive the login form itself.
- CI runs headless, often on Selenium Grid or a cloud grid in parallel, with screenshots and logs kept as artifacts for every failure.
- Many teams run new UI tests in Playwright while keeping working Selenium suites: the page object design carries over unchanged.
Interview angle
“How would you design a Selenium framework in Java?”
A base test creates a fresh driver per test (headless in CI, configurable browser and base URL), an explicit WebDriverWait, a screenshot-on-failure hook, and always quits the driver. Page objects own their By locators (stable attributes like test ids and names, never absolute XPath) and their waits, expose user-level methods, and return the next page for fluent tests; assertions stay in the tests. Data setup and logins go through the API. Tests run in parallel with JUnit or TestNG, on Selenium Grid when needed, with reports and screenshots in CI.
Clean up
The full project
Every file from this lab, as it is after the last step.