QA and Test Automation · Lab 4 of 35

Your first Java test project: Maven, JUnit 5 and a first API check

Install JDK 21 and Maven, build a test project from an empty folder, code ShopRung's coupon and shipping rules in cents, cover every boundary with parameterized JUnit 5 tests, solve four SDET interview programs with tests, and write a first API check of the running shop.

⏱ 75 minBeginner💸 Free8 stepsJava + Python

Java 21 (Temurin or OpenJDK)Maven 3.9JUnit 5.11java.net.http.HttpClientShopRungPython 3.12 + pytest (second path)

Overview video

1 / 7

0 of 8 steps done

What you will build

A real Maven test project, written line by line from an empty folder, with 40 passing tests in three classes:

  • PricingTest: ShopRung's money rules (SAVE10, FLAT5, the expired WELCOME15, free shipping from $75.00, rounding half a cent up), coded in whole cents and tested on every boundary with @ParameterizedTest and @CsvSource, assertAll and assertThrows.
  • PuzzlesTest: the four programs SDET interviews ask for most (reverse the words, find duplicates with a Map, palindrome, count characters), each with tests for the edge cases interviewers look for.
  • ShopRungApiTest: your first black-box check of the running shop over HTTP, using only the JDK. It skips itself cleanly when ShopRung is not running, and it catches a real ShopRung bug when you switch that bug on.

Prefer Python? Switch to Python at the top of the steps: the same project, test for test, with pytest.

Before you start

  • Java basics: classes, methods, if and loops. New to Java? Watch Java for testers first. Maven and JUnit 5 explains the ideas this lab puts into practice.
  • ShopRung installed, as in lab 1 setup. You need it running from step 7.
  • You have done Test cases for a checkout: this lab automates some of the same boundaries.
  • A code editor: IntelliJ IDEA (the free version is enough) or VS Code with the Extension Pack for Java. Every step also works with just a terminal.

Setup

S1Install Java 21 (the JDK)

The JDK (Java Development Kit) has the compiler javac and the java command. Java 21 is a long-term support release, which most companies use for test projects. Temurin is a free, open-source build of it.

macOS: Homebrew installs Temurin 21 where macOS looks for Java, and the JAVA_HOME line tells Maven to use it. Linux: the line below is for Ubuntu and Debian (Fedora: sudo dnf install java-21-openjdk-devel). If you use SDKMAN, run sdk list java, pick the newest 21.x line that ends in -tem, and sdk install java with that id. Windows: after the install, open a new terminal so it finds java.

Run
brew install --cask temurin@21
echo 'export JAVA_HOME=$(/usr/libexec/java_home -v 21)' >> ~/.zshrc
source ~/.zshrc
java -version
You should seeyour text will differ: the model writes it
openjdk version "21.0.9" 2025-10-21 LTS
OpenJDK Runtime Environment Temurin-21.0.9+10 (build 21.0.9+10-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.9+10 (build 21.0.9+10-LTS, mixed mode, sharing)

S2Install Maven

Maven builds Java projects: it downloads the libraries your pom.xml asks for (like JUnit), compiles your code and runs your tests. Any Maven from 3.8 works for this lab.

Windows has no one-line installer for Maven, so the commands download the official zip, unzip it to C:\tools, and add its bin folder to your PATH. Open a new terminal afterwards. (If you have Scoop or Chocolatey, scoop install maven or choco install maven also work.)

Run
brew install maven
mvn -v
You should seeyour text will differ: the model writes it
Apache Maven 3.9.11 (3e54c93a704957b63ee3494413a2b544fd3d825b)
Maven home: ...
Java version: 21.0.9, vendor: Eclipse Adoptium, runtime: ...

S3Check Maven uses Java 21

Look at the Java version: line of mvn -v. It must start with 21. If it shows another version (Homebrew's Maven brings its own newest Java), JAVA_HOME is not set in this terminal: on macOS run source ~/.zshrc and check echo $JAVA_HOME prints a path with 21 in it.

S4Python path only: Python 3.12 or newer

Only if you take the Python path. Install Python from python.org (Windows and macOS) or your package manager, then check the version. On Windows, use py where the steps say python3.

Run
python3 --version
You should see
Python 3.12.x (or newer)
1

Create the Maven project

An empty project that Maven can build: the standard folders and a pom.xml.

Maven expects a fixed layout, and every Java team uses it: src/main/java for the code, src/test/java for the tests, and pom.xml (the Project Object Model) at the top. Folders follow the package name, so dev.algorung.shop lives in dev/algorung/shop.

Make the folders. Open a terminal where you keep your labs (for example ~/qa-labs) and run the command for your system:

# macOS and Linux
mkdir -p shoprung-tests/src/main/java/dev/algorung/shop shoprung-tests/src/test/java/dev/algorung/shop
cd shoprung-tests

# Windows PowerShell
mkdir shoprung-tests\src\main\java\dev\algorung\shop, shoprung-tests\src\test\java\dev\algorung\shop
cd shoprung-tests

Now create pom.xml in the shoprung-tests folder with the content below. You could generate a project with mvn archetype:generate, but writing it yourself once means you know what every line does. Then run mvn test. The first run downloads Maven's plugins and JUnit (a minute or two); later runs take seconds.

pom.xml
<?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-tests</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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.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>
  1. **groupId, artifactId, version** name your project. groupId is usually your company's domain backwards.line 6
  2. Compile for Java 21. release also stops you from using anything newer than Java 21 by accident.line 11
  3. Read the source files as UTF-8 on every machine, so a test with "café" works on Windows too.line 12
  4. JUnit 5.11, pinned. A pinned version gives the same build today and in a year. (JUnit 6 came out in 2025; everything in this lab works the same there.)line 13
  5. junit-jupiter brings the JUnit 5 API, the parameterized tests module and the engine that runs them.line 19
  6. test scope: JUnit is only on the classpath while compiling and running tests, never in the shipped code.line 21
  7. The compiler plugin, pinned too. Maven picks a default version when you do not, and that default changes between Maven versions.line 30
  8. **Surefire** is the plugin that runs tests during mvn test. It finds every class whose name ends in Test under src/test/java.line 34
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------< dev.algorung:shoprung-tests >--------------------
[INFO] Building shoprung-tests 0.1.0
...
[INFO] No sources to compile
...
[INFO] No tests to run.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
Why this way? Maven's layout and a pom.xml are the same in every Java team, so a project you set up once by hand is a project you can read anywhere. In Python, the virtual environment (.venv) keeps this project's packages apart from every other project on your machine.
Stuck on this step?
mvn: command not found (or "not recognized" on Windows)
Maven is not on your PATH in this terminal. Open a new terminal. On Windows check the PATH line in setup ran, then run mvn -v again.
Non-parseable POM or Unrecognised tag
A tag is not closed or is misspelled. Copy the whole file again with the Copy button; the line number in the message points at the problem.
Windows: Activate.ps1 cannot be loaded because running scripts is disabled
Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, answer Y, then activate again.
2

Your first class and your first tests

Money formatting and the shipping rule in code, with six passing tests.

You will put ShopRung's money rules (requirements PRICE-1 to PRICE-10) into a small class and test it. Testing the rules directly, with no browser and no server, is a unit test: it runs in milliseconds and points straight at the broken rule.

One decision first: money is whole cents in a long, so $50.00 is 5000. Never use double for money: 0.1 + 0.2 is 0.30000000000000004 in Java. ShopRung itself stores cents for the same reason.

Create the two files below: the class in src/main/java/..., the test in src/test/java/.... A test is a method with @Test. assertEquals(expected, actual) fails the test when the two differ; the expected value always comes first, so the failure message reads the right way round.

The shipping rule (PRICE-9) is a boundary: $4.99 below $75.00, free from $75.00. Instead of five copies of the same test, @ParameterizedTest runs one method once per row of @CsvSource. Each row is one test case: the boundary, one cent below it, one above it, and the edge cases.

src/main/java/dev/algorung/shop/Pricing.java
package dev.algorung.shop;

/**
 * ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
 * Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
 */
public final class Pricing {
    public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
    public static final long SHIPPING = 499;             // $4.99

    private Pricing() {}

    /** 1250 becomes "$12.50" (PRICE-1). */
    public static String money(long cents) {
        if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }

    /** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
    public static long shipping(long afterDiscount) {
        if (afterDiscount == 0) return 0;
        return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
    }
}
  1. Named constants instead of magic numbers. 7_500: Java lets you write underscores in numbers to make them readable.line 8
  2. A class of static helpers: a private constructor stops anyone creating an instance.line 11
  3. %02d pads the cents to two digits, so 5 cents prints as $0.05, not $0.5.line 16
  4. ShopRung shows $0.00 shipping for an empty cart. Your code matches the real shop, not your guess.line 21
  5. The whole boundary is in this one character. > instead of >= is exactly ShopRung's free-shipping-boundary bug.line 22
src/test/java/dev/algorung/shop/PricingTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class PricingTest {
    @Test
    void moneyHasADollarSignAndTwoDecimals() {
        assertEquals("$12.50", Pricing.money(1250));
        assertEquals("$0.05", Pricing.money(5));
    }

    @ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
    @CsvSource({
        "7499, 499",  // one cent below the edge
        "7500, 0",    // exactly on the edge: free
        "7501, 0",
        "1,    499",
        "0,    0",    // an empty cart ships nothing
    })
    void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
        assertEquals(expected, Pricing.shipping(afterDiscount));
    }
}
  1. A static import lets you write assertEquals(...) instead of Assertions.assertEquals(...).line 3
  2. Test classes do not need to be public in JUnit 5. The name ends in Test, which is how Surefire finds it.line 9
  3. Expected first, actual second.line 12
  4. name sets how each row shows in the report: 7499 cents after the discount -> shipping 499.line 16
  5. One row per case. JUnit converts each value to the parameter type (long here) for you.line 18
  6. The parameters match the columns, in order.line 24
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.algorung.shop.PricingTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Stuck on this step?
No tests to run although the test file exists
The test is in the wrong folder or the class name does not end in Test. It must be src/test/java/dev/algorung/shop/PricingTest.java, and the first line must be package dev.algorung.shop;.
package org.junit.jupiter.api does not exist
The test file is under src/main/java. JUnit has test scope, so it only exists for files under src/test/java. Move the file.
Python: ModuleNotFoundError: No module named 'pricing'
Run pytest from the project folder, the one with pricing.py in it, and keep the test file in that same folder.
3

Coupons, and every boundary in one table

The three coupons and the cart totals, with nine boundary rows from lab 1 as tests.

Now the coupon rules: SAVE10 takes 10% off from $50.00 (PRICE-3), FLAT5 takes $5.00 off from $20.00 (PRICE-4), WELCOME15 expired on 31 December 2025 (PRICE-5), codes are not case-sensitive (PRICE-2), and an unknown code gets "No coupon called ..." (PRICE-7). A Java enum fits: a fixed list of named values, each with its own data. The messages are copied from ShopRung, word for word.

Then totals() adds them up: total = subtotal - discount + shipping (PRICE-10), with shipping worked out after the discount (PRICE-9). A record holds the four numbers. Records get equals for free, so one assertEquals compares all four.

The table in the test is the boundary analysis from lab 1, now as code. Every row is a real ShopRung cart: 4 notebooks are $50.00, the hoodie is $49.99, the keyboard is $75.00. An empty cell (the coupon column in two rows) arrives as null, which means "no coupon".

src/main/java/dev/algorung/shop/Coupon.java
package dev.algorung.shop;

import java.time.LocalDate;
import java.util.Locale;

/** ShopRung's three coupons (PRICE-2 to PRICE-7), with the same rules and messages as the shop. */
public enum Coupon {
    SAVE10(true, 10, 5_000, null),                       // 10% off from $50.00
    FLAT5(false, 500, 2_000, null),                      // $5.00 off from $20.00
    WELCOME15(true, 15, 0, LocalDate.of(2025, 12, 31));  // expired

    private final boolean percent;
    private final long amount;      // a percent, or cents
    private final long minSubtotal; // cents
    private final LocalDate expiresOn;

    Coupon(boolean percent, long amount, long minSubtotal, LocalDate expiresOn) {
        this.percent = percent;
        this.amount = amount;
        this.minSubtotal = minSubtotal;
        this.expiresOn = expiresOn;
    }

    /** Finds a coupon by code. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7). */
    public static Coupon of(String code) {
        String c = code == null ? "" : code.trim().toUpperCase(Locale.ROOT);
        for (Coupon coupon : values()) {
            if (coupon.name().equals(c)) return coupon;
        }
        throw new IllegalArgumentException("No coupon called " + (c.isEmpty() ? "(empty)" : c));
    }

    /** Why this coupon cannot be used, or null when it can. */
    public String problem(long subtotal, LocalDate today) {
        if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
        if (subtotal < minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
        return null;
    }

    /** The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6). */
    public long discount(long subtotal) {
        if (percent) return (subtotal * amount + 50) / 100;
        return Math.min(amount, subtotal); // a fixed amount never makes the total negative
    }
}
  1. Each constant passes its data to the constructor: percent or not, the amount, the minimum subtotal and the expiry date.line 8
  2. Locale.ROOT makes upper-casing the same on every computer. With a Turkish locale, "i".toUpperCase() is not "I".line 26
  3. The same message ShopRung shows, including (empty) for an empty code.line 30
  4. The date is passed in, not read from the clock inside. That is what makes the rule testable on any day.line 35
  5. Below the minimum is refused, so exactly the minimum is accepted: "$50.00 or more".line 36
  6. Rounding half a cent up in whole numbers (PRICE-6): 10% of 5045 cents is 504.5, and (50450 + 50) / 100 = 505. No floating point anywhere.line 42
src/main/java/dev/algorung/shop/Pricing.java 10 new or changed lines
package dev.algorung.shop;

import java.time.LocalDate;

/**
 * ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
 * Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
 */
public final class Pricing {
    public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
    public static final long SHIPPING = 499;             // $4.99

    /** The four numbers a cart shows. */
    public record Totals(long subtotal, long discount, long shipping, long total) {}

    private Pricing() {}

    /** 1250 becomes "$12.50" (PRICE-1). */
    public static String money(long cents) {
        if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }

    /** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
    public static long shipping(long afterDiscount) {
        if (afterDiscount == 0) return 0;
        return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
    }

    /** Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8). */
    public static Totals totals(long subtotal, Coupon coupon, LocalDate today) {
        if (subtotal < 0) throw new IllegalArgumentException("subtotal must not be negative: " + subtotal);
        long discount = 0;
        if (coupon != null && coupon.problem(subtotal, today) == null) discount = coupon.discount(subtotal);
        long shipping = shipping(subtotal - discount);
        return new Totals(subtotal, discount, shipping, subtotal - discount + shipping);
    }
}
  1. A record: an immutable holder with a constructor, getters (t.total()), equals and a readable toString, all generated.line 14
  2. A coupon that does not apply simply gives no discount (PRICE-8), like ShopRung's cart.line 34
  3. Shipping is decided on the amount **after** the discount.line 35
src/test/java/dev/algorung/shop/PricingTest.java 19 new or changed lines
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;

import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class PricingTest {
    // A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
    static final LocalDate TODAY = LocalDate.of(2026, 11, 30);

    @Test
    void moneyHasADollarSignAndTwoDecimals() {
        assertEquals("$12.50", Pricing.money(1250));
        assertEquals("$0.05", Pricing.money(5));
    }

    @ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
    @CsvSource({
        "7499, 499",  // one cent below the edge
        "7500, 0",    // exactly on the edge: free
        "7501, 0",
        "1,    499",
        "0,    0",    // an empty cart ships nothing
    })
    void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
        assertEquals(expected, Pricing.shipping(afterDiscount));
    }

    @ParameterizedTest(name = "{0} cents with {1} -> -{2} +{3} = {4}")
    @CsvSource({
        // subtotal, coupon, discount, shipping, total
        "5000, SAVE10, 500, 499, 4999",   // 4 x Clean Code Notebook: SAVE10 on the edge
        "4999, SAVE10,   0, 499, 5498",   // the Hoodie: one cent short
        "5045, save10, 505, 499, 5039",   // 10% of $50.45 is $5.045: half a cent rounds up
        "2000, FLAT5,  500, 499, 1999",   // the T-Shirt: FLAT5 on the edge
        "1999, FLAT5,    0, 499, 2498",
        "7500,       ,   0,   0, 7500",   // the Keyboard, no coupon: free shipping on the edge
        "7499,       ,   0, 499, 7998",
        "8000, FLAT5,  500,   0, 7500",   // shipping is counted AFTER the discount
        "7500, FLAT5,  500, 499, 7499",   // ... so a coupon can lose free shipping
    })
    void cartTotals(long subtotal, String code, long discount, long shipping, long total) {
        Coupon coupon = code == null ? null : Coupon.of(code);
        Totals t = Pricing.totals(subtotal, coupon, TODAY);
        assertEquals(new Totals(subtotal, discount, shipping, total), t);
    }
}
  1. A fixed date. A test that reads today's date can pass today and fail next year.line 13
  2. TC-06 from lab 1: SAVE10 exactly on its edge. In ShopRung this cart shows a total of $49.99.line 36
  3. Lower-case code (PRICE-2) and the rounding rule in one row: 5 sticker packs and the mouse.line 38
  4. An empty cell becomes null. To pass an empty string instead, write ''.line 41
  5. 4 T-shirts minus FLAT5 is exactly $75.00, so shipping is free. The next row shows the opposite.line 43
  6. One assertion compares all four numbers, because records compare field by field.line 49
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.algorung.shop.PricingTest
[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Why this way? A table of cases makes the boundaries visible at a glance, and adding a case is one line. Reviewers can check the test data against the requirements without reading any test code.
Stuck on this step?
ParameterResolutionException or ArgumentConversionException
A row has a different number of values than the method has parameters, or a value that is not a number in a long column. Count the commas in the row the message names.
cannot find symbol: class Totals
Check the import import dev.algorung.shop.Pricing.Totals; at the top of the test. Totals lives inside Pricing.
4

assertAll and assertThrows

See every wrong number at once, and test that bad input is refused.

Two more tools you will use in every test project:

  • assertAll runs every check inside it and reports all the failures together. A plain list of assertEquals stops at the first one, so you fix one number, run again, and find the next.
  • assertThrows passes only when the code throws the exception you name. It returns the exception, so you can also check its message.

The new tests check what a customer sees ($49.99, not 4999), that each coupon message matches ShopRung exactly, and that an impossible input, a negative subtotal, is refused instead of giving a strange total.

src/test/java/dev/algorung/shop/PricingTest.java 20 new or changed lines
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class PricingTest {
    // A fixed "today", so the expired-coupon rule gives the same answer on every day the tests run.
    static final LocalDate TODAY = LocalDate.of(2026, 11, 30);

    @Test
    void moneyHasADollarSignAndTwoDecimals() {
        assertEquals("$12.50", Pricing.money(1250));
        assertEquals("$0.05", Pricing.money(5));
    }

    @ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
    @CsvSource({
        "7499, 499",  // one cent below the edge
        "7500, 0",    // exactly on the edge: free
        "7501, 0",
        "1,    499",
        "0,    0",    // an empty cart ships nothing
    })
    void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
        assertEquals(expected, Pricing.shipping(afterDiscount));
    }

    @ParameterizedTest(name = "{0} cents with {1} -> -{2} +{3} = {4}")
    @CsvSource({
        // subtotal, coupon, discount, shipping, total
        "5000, SAVE10, 500, 499, 4999",   // 4 x Clean Code Notebook: SAVE10 on the edge
        "4999, SAVE10,   0, 499, 5498",   // the Hoodie: one cent short
        "5045, save10, 505, 499, 5039",   // 10% of $50.45 is $5.045: half a cent rounds up
        "2000, FLAT5,  500, 499, 1999",   // the T-Shirt: FLAT5 on the edge
        "1999, FLAT5,    0, 499, 2498",
        "7500,       ,   0,   0, 7500",   // the Keyboard, no coupon: free shipping on the edge
        "7499,       ,   0, 499, 7998",
        "8000, FLAT5,  500,   0, 7500",   // shipping is counted AFTER the discount
        "7500, FLAT5,  500, 499, 7499",   // ... so a coupon can lose free shipping
    })
    void cartTotals(long subtotal, String code, long discount, long shipping, long total) {
        Coupon coupon = code == null ? null : Coupon.of(code);
        Totals t = Pricing.totals(subtotal, coupon, TODAY);
        assertEquals(new Totals(subtotal, discount, shipping, total), t);
    }

    @Test
    void save10OnFourNotebooks() {
        Totals t = Pricing.totals(4 * 1250, Coupon.SAVE10, TODAY);
        assertAll("4 x Clean Code Notebook with SAVE10",
            () -> assertEquals("$50.00", Pricing.money(t.subtotal())),
            () -> assertEquals("$5.00", Pricing.money(t.discount())),
            () -> assertEquals("$4.99", Pricing.money(t.shipping())),
            () -> assertEquals("$49.99", Pricing.money(t.total())));
    }

    @Test
    void anUnknownCouponIsRefusedByName() {
        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Coupon.of("SAVE20"));
        assertEquals("No coupon called SAVE20", e.getMessage());
    }

    @Test
    void couponMessagesMatchTheShop() {
        assertAll(
            () -> assertEquals("This coupon has expired", Coupon.WELCOME15.problem(10_000, TODAY)),
            () -> assertEquals("This coupon needs a subtotal of at least $50.00", Coupon.SAVE10.problem(4_999, TODAY)),
            () -> assertNull(Coupon.SAVE10.problem(5_000, TODAY)));
    }

    @Test
    void aNegativeSubtotalIsRefused() {
        assertThrows(IllegalArgumentException.class, () -> Pricing.totals(-1, null, TODAY));
    }
}
  1. The first argument is a heading for the failure report. Each lambda (() -> ...) is one check.line 58
  2. The code under test goes in a lambda, so JUnit can run it and catch what it throws.line 67
  3. Check the message too: "it threw something" is a weak test.line 68
  4. null means "no problem": exactly $50.00 is accepted.line 76
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.algorung.shop.PricingTest
[INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
5

Watch your tests catch a bug

Break the code on purpose, see exactly which tests fail, then put it back.

A test you have never seen fail might not be able to fail. So break the code: in Coupon.java, change subtotal < minSubtotal to subtotal <= minSubtotal. One character. Now a coupon needs more than its minimum, which is ShopRung's coupon-boundary bug.

Run the tests. Four fail, and each failure says what was expected and what came back. Look at which ones: the $50.00 and $20.00 rows, the four-notebook cart and the message check. The $49.99 and $19.99 rows still pass. Only the tests sitting exactly on the boundary catch this bug.

Change <= back to < and run mvn test again: 19 tests pass.

src/main/java/dev/algorung/shop/Coupon.java 1 new line
    /** Why this coupon cannot be used, or null when it can. */
    public String problem(long subtotal, LocalDate today) {
        if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
        if (subtotal <= minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
        return null;
    }
  1. The bug: <= instead of <. Put it in, run the tests, then take it out again.line 4
Run
mvn test
You should seeyour text will differ: the model writes it
[ERROR] Tests run: 19, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 0.07 s <<< FAILURE! -- in dev.algorung.shop.PricingTest
...
[ERROR] Failures:
[ERROR]   PricingTest.cartTotals:52 expected: <Totals[subtotal=5000, discount=500, shipping=499, total=4999]> but was: <Totals[subtotal=5000, discount=0, shipping=499, total=5499]>
[ERROR]   PricingTest.cartTotals:52 expected: <Totals[subtotal=2000, discount=500, shipping=499, total=1999]> but was: <Totals[subtotal=2000, discount=0, shipping=499, total=2499]>
[ERROR]   PricingTest.couponMessagesMatchTheShop:73 Multiple Failures (1 failure)
	org.opentest4j.AssertionFailedError: expected: <null> but was: <This coupon needs a subtotal of at least $50.00>
[ERROR]   PricingTest.save10OnFourNotebooks:58 4 x Clean Code Notebook with SAVE10 (2 failures)
	org.opentest4j.AssertionFailedError: expected: <$5.00> but was: <$0.00>
	org.opentest4j.AssertionFailedError: expected: <$49.99> but was: <$54.99>
[INFO]
[ERROR] Tests run: 19, Failures: 4, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE
Why this way? This is mutation testing done by hand: change the code a little and check a test notices. The Mutation testing lab does it automatically with PIT, across the whole codebase.
Stuck on this step?
All 19 tests still pass with the bug in
You edited a copy, or the file is not saved. Save Coupon.java and run mvn test again; Maven recompiles changed files by itself.
6

The SDET interview programs, with tests

Reverse the words, find duplicates with a Map, check a palindrome and count characters, each with edge-case tests.

SDET interviews almost always include a short coding round, and these four programs come up again and again. What lifts an answer is the same thing that lifts a test suite: the edge cases. Empty text, one word, extra spaces, upper and lower case, punctuation.

  • Reverse the words: split on any run of spaces, then walk the array backwards.
  • Duplicates: count with a Map, one pass, O(n). A LinkedHashMap keeps the order items first appeared. The test data is ShopRung SKUs, like a duplicate check on an order export.
  • Palindrome: two pointers walking in from both ends, skipping anything that is not a letter or digit. No new string needed.
  • Count characters: Map.merge adds 1 to the count, or puts 1 if the character is new.

Write the tests first if you like: they are the interviewer's follow-up questions written down. @ValueSource is the simple sibling of @CsvSource: one value per test.

src/main/java/dev/algorung/shop/Puzzles.java
package dev.algorung.shop;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** The four programs SDET interviews ask for most, written the way you would on a whiteboard. */
public final class Puzzles {
    private Puzzles() {}

    /** "  hello   big world " becomes "world big hello". Extra spaces are dropped. */
    public static String reverseWords(String text) {
        String[] words = text.trim().split("\\s+");
        StringBuilder out = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            out.append(words[i]);
            if (i > 0) out.append(' ');
        }
        return out.toString();
    }

    /** The items that appear more than once, in the order they first appeared. */
    public static List<String> duplicates(List<String> items) {
        Map<String, Integer> counts = new LinkedHashMap<>();
        for (String item : items) {
            counts.merge(item, 1, Integer::sum);
        }
        List<String> result = new ArrayList<>();
        for (Map.Entry<String, Integer> e : counts.entrySet()) {
            if (e.getValue() > 1) result.add(e.getKey());
        }
        return result;
    }

    /** True when the letters and digits read the same both ways, ignoring case: "Never odd or even". */
    public static boolean isPalindrome(String text) {
        int left = 0, right = text.length() - 1;
        while (left < right) {
            char a = text.charAt(left), b = text.charAt(right);
            if (!Character.isLetterOrDigit(a)) { left++; continue; }
            if (!Character.isLetterOrDigit(b)) { right--; continue; }
            if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
            left++;
            right--;
        }
        return true;
    }

    /** How many times each character appears, spaces left out: "hello" gives {h=1, e=1, l=2, o=1}. */
    public static Map<Character, Integer> countCharacters(String text) {
        Map<Character, Integer> counts = new LinkedHashMap<>();
        for (char c : text.toCharArray()) {
            if (c != ' ') counts.merge(c, 1, Integer::sum);
        }
        return counts;
    }
}
  1. "\\s+" is the regular expression \s+: one or more whitespace characters (spaces, tabs, new lines). trim() first, or leading spaces give an empty first word.line 14
  2. If the key is new, store 1; otherwise add 1 to what is there. One line instead of an if.line 27
  3. Two pointers: O(n) time and no extra memory. Interviewers often ask for this after a first "reverse the string and compare" answer.line 38
  4. Compare ignoring case, so "Never odd or even" counts.line 43
src/test/java/dev/algorung/shop/PuzzlesTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

class PuzzlesTest {

    @ParameterizedTest(name = "[{0}] -> [{1}]")
    @CsvSource({
        "'hello big world', 'world big hello'",
        "'  hello   big world ', 'world big hello'",  // extra spaces
        "one, one",                                   // a single word
        "'', ''",                                     // empty text
    })
    void reverseWords(String text, String expected) {
        assertEquals(expected, Puzzles.reverseWords(text));
    }

    @Test
    void reverseWordsRefusesNull() {
        assertThrows(NullPointerException.class, () -> Puzzles.reverseWords(null));
    }

    @Test
    void duplicateSkusInFirstSeenOrder() {
        List<String> skus = List.of("BK-101", "MG-201", "BK-101", "ST-501", "MG-201", "BK-101");
        assertEquals(List.of("BK-101", "MG-201"), Puzzles.duplicates(skus));
    }

    @Test
    void noDuplicates() {
        assertEquals(List.of(), Puzzles.duplicates(List.of("BK-101", "MG-201")));
        assertEquals(List.of(), Puzzles.duplicates(List.of()));
    }

    @ParameterizedTest
    @ValueSource(strings = {"racecar", "Never odd or even", "A man, a plan, a canal: Panama", "a", ""})
    void palindromes(String text) {
        assertTrue(Puzzles.isPalindrome(text));
    }

    @ParameterizedTest
    @ValueSource(strings = {"ShopRung", "ab", "abca"})
    void notPalindromes(String text) {
        assertFalse(Puzzles.isPalindrome(text));
    }

    @Test
    void countCharacters() {
        assertEquals(Map.of('h', 1, 'e', 1, 'l', 2, 'o', 1), Puzzles.countCharacters("hello"));
        assertEquals(Map.of('a', 2, 'b', 1), Puzzles.countCharacters("a b a"));
        assertEquals(Map.of(), Puzzles.countCharacters(""));
    }
}
  1. Single quotes keep the spaces inside a CSV value. Without them JUnit trims each value.line 20
  2. '' is an empty string. An empty cell without quotes would be null.line 22
  3. Decide what null should do and pin it down with a test, so nobody changes it by accident.line 30
  4. One test per value. "a" and "" are the edge cases: both read the same backwards.line 46
  5. Two maps are equal when they hold the same pairs, in any order.line 59
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.algorung.shop.PricingTest
[INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PricingTest
[INFO] Running dev.algorung.shop.PuzzlesTest
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in dev.algorung.shop.PuzzlesTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 35, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Stuck on this step?
reverseWords returns the words with a space at the start
You split before trimming. " hello".split("\\s+") gives ["", "hello"]. Call trim() first.
7

A first API check of the running ShopRung

Call the real shop over HTTP from a JUnit test, and skip cleanly when it is not running.

Unit tests check your copy of the rules. This test checks the real shop, from the outside, the way a customer's browser talks to it: send an HTTP request, check the status code and the body. That is a black-box test: it knows nothing about ShopRung's code.

Java has had an HTTP client built in since Java 11, java.net.http.HttpClient, so you need no new library. Later labs use REST Assured, which reads more nicely; this one shows what any HTTP test does underneath.

An API test needs the server running. If it is not, the tests should be skipped, not failed: a failure means "the shop is broken", and that would be a lie. JUnit's Assumptions.assumeTrue does this: when the assumption is false, the test is reported as skipped with your message.

First run the tests with ShopRung stopped and see five skipped tests. Then start ShopRung as in lab 1 and run them again. ShopRung on another port? Set SHOPRUNG_URL, for example SHOPRUNG_URL=http://localhost:8081 mvn test (PowerShell: $env:SHOPRUNG_URL="http://localhost:8081"; mvn test).

src/test/java/dev/algorung/shop/ShopRungApiTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/** Black-box checks against the running ShopRung. Every test is skipped when ShopRung is not running. */
class ShopRungApiTest {
    static final String BASE = System.getenv().getOrDefault("SHOPRUNG_URL", "http://localhost:8080");
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();

    static HttpResponse<String> get(String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
            .timeout(Duration.ofSeconds(5))
            .GET()
            .build();
        return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
    }

    static HttpResponse<String> post(String path, String json) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(BASE + path))
            .timeout(Duration.ofSeconds(5))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();
        return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
    }

    static boolean running;

    @BeforeAll
    static void checkShopRungOnce() {
        try {
            running = get("/api/health").statusCode() == 200;
        } catch (Exception e) {
            running = false; // connection refused: nothing is listening on that port
        }
    }

    @BeforeEach
    void needsShopRung() {
        assumeTrue(running, "ShopRung is not running at " + BASE + ". Start it with npm start.");
    }

    @Test
    void healthSaysUp() throws Exception {
        HttpResponse<String> r = get("/api/health");
        assertEquals(200, r.statusCode());
        assertTrue(r.body().contains("\"status\":\"UP\""), r.body());
    }

    @Test
    void searchIsNotCaseSensitive() throws Exception { // SRCH-2
        String lower = get("/api/products?q=mug").body();
        String upper = get("/api/products?q=MUG").body();
        assertTrue(lower.contains("\"count\":2"), lower);
        assertEquals(lower, upper);
    }

    @Test
    void aOneLetterSearchIsRefused() throws Exception { // SRCH-3, NF-4
        HttpResponse<String> r = get("/api/products?q=m");
        assertEquals(400, r.statusCode());
        assertTrue(r.body().contains("\"error\":\"query_too_short\""), r.body());
    }

    @Test
    void theRedMugIsOutOfStock() throws Exception { // CART-4: product 5 has stock 0
        String body = get("/api/products/5").body();
        assertTrue(body.contains("\"stock\":0") && body.contains("\"inStock\":false"), body);
    }

    @Test
    void aWrongPasswordGetsTheSameMessage() throws Exception { // ACC-6
        HttpResponse<String> r = post("/api/auth/login", "{\"email\":\"alice@shoprung.test\",\"password\":\"wrong-1\"}");
        assertEquals(401, r.statusCode());
        assertTrue(r.body().contains("Email or password is wrong"), r.body());
    }
}
  1. The address comes from an environment variable, with ShopRung's default as the fallback. The same tests then run against any copy of the shop.line 18
  2. Always set timeouts. Without them a test against a hung server waits forever and blocks the whole run.line 19
  3. Read the response body as text.line 26
  4. The request body, here a small JSON object written by hand.line 33
  5. Runs once, before any test in the class: one health check instead of five.line 40
  6. Runs before each test. When ShopRung is down, each test is reported as skipped with this message.line 51
  7. Two products have "mug" in their name: Green Build Mug and Red Build Mug. contains on raw JSON is fine for a first check; the REST Assured lab reads JSON properly.line 65
  8. SRCH-2: "mug" and "MUG" must give the same answer.line 66
  9. A one-letter search is refused with 400 and query_too_short (SRCH-3), as JSON (NF-4).line 72
  10. ACC-6: a wrong password gets 401 and the same message as an unknown email.line 85
Run
# ShopRung stopped:
mvn test
# then start ShopRung in another terminal and run again:
mvn test
You should seeyour text will differ: the model writes it
[INFO] Running dev.algorung.shop.ShopRungApiTest
[WARNING] Tests run: 5, Failures: 0, Errors: 0, Skipped: 5, Time elapsed: 0.04 s -- in dev.algorung.shop.ShopRungApiTest
...
[WARNING] Tests run: 40, Failures: 0, Errors: 0, Skipped: 5
[INFO] BUILD SUCCESS

(second run, ShopRung running)
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.3 s -- in dev.algorung.shop.ShopRungApiTest
...
[INFO] Tests run: 40, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Why this way? Skipping is honest: the report says "not checked" instead of a red failure that sends someone hunting for a bug that is not there. In CI you start the app first, so the API tests always run there.
Stuck on this step?
The API tests are skipped although ShopRung is running
Check the port. Open http://localhost:8080/api/health in a browser: it must show "status":"UP". If ShopRung runs on another port, set SHOPRUNG_URL as in the text above.
searchIsNotCaseSensitive fails with "count":0
The search-case bug is switched on. Check the yellow bar in the shop, or run the bug switch command with "enabled":[] to turn every bug off.
8

Run part of the suite, and read the report

Run one class or one test, and find the report files that CI reads.

When one test fails you do not want to run everything. Maven's -Dtest picks a class, or one method after #. Keep the quotes: they make the command work the same in zsh, bash and PowerShell.

Every run also writes a report to target/surefire-reports/: a .txt summary per class, and a TEST-<class>.xml file in the JUnit XML format. Every CI system (GitHub Actions, Jenkins, GitLab) reads that XML to show which tests failed. pytest writes the same format with --junitxml.

Run
mvn test "-Dtest=PuzzlesTest"
mvn test "-Dtest=PricingTest#cartTotals"
ls target/surefire-reports
You should seeyour text will differ: the model writes it
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0
...
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
...
TEST-dev.algorung.shop.PricingTest.xml
dev.algorung.shop.PricingTest.txt
Why this way? A suite of 40 tests runs in a second, but real suites take minutes. Running exactly the failing test is how you stay fast while fixing it.
Stuck on this step?
No tests matching pattern "PricingTest#cartTotals" were executed!
Check the spelling: class and method names are case-sensitive. Use the method name, not the display name of a row.

Check it works

Two checks. First, with ShopRung running and no bugs on, the whole suite passes: 40 tests, no failures, none skipped.

Second, prove the API test can fail. Switch on ShopRung's search-case bug (search becomes case-sensitive), run the suite, and exactly one test fails: searchIsNotCaseSensitive (Python: test_search_is_not_case_sensitive), because "mug" now finds nothing. Then switch the bugs off and run again: all green.

# bug on (macOS and Linux; PowerShell commands are in the Windows tab below)
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'
mvn test        # or: pytest

# bugs off
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'
Test
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'
You should see
{"mystery":false,"active":["search-case"],"known":{...}}

mvn test:
[ERROR] Failures:
[ERROR]   ShopRungApiTest.searchIsNotCaseSensitive:65 {"count":0,"items":[]} ==> expected: <true> but was: <false>
[ERROR] Tests run: 40, Failures: 1, Errors: 0, Skipped: 0

pytest:
FAILED test_shoprung_api.py::test_search_is_not_case_sensitive - assert 0 == 2
1 failed, 39 passed in 0.08s

Troubleshooting

error: release version 21 not supported

Maven is running with an older Java. Run mvn -v and look at Java version. Set JAVA_HOME to your Java 21 (macOS: export JAVA_HOME=$(/usr/libexec/java_home -v 21)), open a new terminal and try again.

Could not resolve dependencies or Could not transfer artifact on the first run

Maven could not download from Maven Central. Check your internet connection. At work, a company proxy or an internal repository (Nexus, Artifactory) may be required: ask for the settings.xml your team uses and put it in ~/.m2/.

Tests pass in the IDE but mvn test finds none (or the other way round)

Check the class name ends in Test and the file is under src/test/java. Surefire only runs classes that match *Test, Test*, *Tests or *TestCase. Your IDE may run anything you click on.

The IDE shows JUnit imports in red

The IDE has not loaded the pom.xml yet. IntelliJ: right-click pom.xml, then Maven > Sync Project (older versions: Reload project). VS Code: open the folder that contains pom.xml, not a parent folder.

Python: pytest: command not found

The virtual environment is not active in this terminal. Run source .venv/bin/activate (Windows: .venv\Scripts\Activate.ps1); your prompt then starts with (.venv).

What changes in production

  • Pin every version in the pom.xml (or requirements file), plugins included. Many teams also commit the Maven Wrapper (mvn wrapper:wrapper creates mvnw), so everyone and CI build with the exact same Maven.
  • Unit tests and API tests run at different times. Unit tests run on every build and need nothing. API tests need a running app, so CI starts it first, or they move to a separate stage (with Maven, often the Failsafe plugin and classes named *IT).
  • Money is never a double. Real shops use whole cents in a long or BigDecimal with an explicit rounding mode. A test suite that pins the rounding rule, like yours, is how teams catch a rounding change before customers do.
  • The JUnit XML report is the contract with CI. GitHub Actions, Jenkins and GitLab all read target/surefire-reports, show failed tests by name and keep their history.

Interview angle

“How would you test a function that applies a discount coupon, and how do you set up the project?”

I start from the rules: the minimum subtotal, the amount or percentage, the rounding, the expiry date and the messages. Each rule has a boundary, so my cases sit on it and one cent either side: $49.99, $50.00 and $50.45 to check rounding, plus an expired code, a lower-case code and an unknown code. I keep money in whole cents so there are no floating-point surprises, and I pass today's date in so the expiry test never depends on the clock. In JUnit 5 that is a @ParameterizedTest with a @CsvSource table, assertThrows for invalid input and assertAll when one case checks several values. The project is plain Maven with pinned JUnit and Surefire versions, and API tests against the running service are skipped with an assumption when it is down, so a red build always means a real failure.

Clean up

Keep the project: the next lab puts it in Git and opens a pull request. Stop ShopRung with Ctrl+C when you are done, and make sure every bug is off.

Run
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'

Practice

These run in your browser and check your answer.

First character that does not repeat

Another favourite interview question. Write first_unique(text) that returns the first character that appears exactly once in text, or None if there is none. Case matters: "A" and "a" are different. Count first, then walk the text again.

Exercise
def first_unique(text):
    counts = {}
    for c in text:
        counts[c] = counts.get(c, 0) + 1
    # your code here: walk the text again
    return text[0]


print(first_unique("swiss"))
Hint

Loop over `text` a second time and return the first `c` whose count is 1. After the loop, return `None`.

How much more for free shipping?

ShopRung could tell customers how far they are from free shipping. Write cents_to_free_shipping(after_discount): how many more cents the cart needs (after the discount) to reach free shipping at 7500 cents. Return 0 when it is already free. Mind the boundary: at exactly 7500 the answer is 0.

Exercise
FREE_SHIPPING_FROM = 7500


def cents_to_free_shipping(after_discount):
    return FREE_SHIPPING_FROM - after_discount


print(cents_to_free_shipping(7499))
Hint

The difference can go below zero. `max(0, ...)` keeps it at zero.

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip) Download Python project (.zip)