Skip to lesson

TDD kata: a discount calculator, part 2

Marketing wants coupon codes, finance wants a cap, and a manager changes who gets the member bonus. Every change can quietly break an old rule. With a test suite, the break shows up as a red line before it ships.

New rules: a cap on the total discount and coupon codes

A cap is an upper limit on a value. Here the total discount on one order is never more than Rs 500.00, which the code writes as min(MAX_DISCOUNT).

Two rules arrive: a cap on the total discount, and coupon codes such as FLAT100. Each enters the test list first, with its edge cases.

Text
New tests on the list: discount(subtotal, member, coupon)  [ ] 6000.00, member, none      -> 500.00   (15% = 900.00, capped)  [ ] 2000.00, -, FLAT100        -> 300.00   (200.00 sale + 100.00 coupon)  [ ] 3000.00, member, FLAT100   -> 500.00   (450.00 + 100.00, capped)  [ ] 60.00, -, FLAT100          -> 60.00    (never more than the order)  [ ] 400.00, -, WELCOME50       -> 50.00    (coupon without the sale)  [ ] 2000.00, -, DIWALI         -> error "Unknown coupon: DIWALI"

Example 1 · The cap: red against part 1, then green

CapCycle.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Map;
public class CapCycle {    static final BigDecimal MAX_DISCOUNT = new BigDecimal("500.00");
    static BigDecimal part1(BigDecimal subtotal, boolean member) {          // the end of part 1        if (subtotal.compareTo(new BigDecimal("1000.00")) < 0) return new BigDecimal("0.00");        BigDecimal rate = member ? new BigDecimal("0.15") : new BigDecimal("0.10");        return subtotal.multiply(rate).setScale(2, RoundingMode.HALF_UP);    }
    static BigDecimal capped(BigDecimal subtotal, boolean member) {         // the new green        return part1(subtotal, member).min(MAX_DISCOUNT);    }
    static void check(String name, String expected, BigDecimal actual) {        if (new BigDecimal(expected).equals(actual)) {            System.out.println("PASS " + name);        } else {            System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);        }    }
    public static void main(String[] args) {        check("red:   big member orders are capped at 500", "500.00", part1(new BigDecimal("6000.00"), true));        check("green: big member orders are capped at 500", "500.00", capped(new BigDecimal("6000.00"), true));        check("green: small orders are not affected", "300.00", capped(new BigDecimal("2000.00"), true));    }}
Output
FAIL red:   big member orders are capped at 500: expected 500.00 but was 900.00
PASS green: big member orders are capped at 500
PASS green: small orders are not affected

What this code does

  • The new cap test is red against the part 1 code: 15% of 6000.00 is 900.00. One method call, min(MAX_DISCOUNT), makes it green.
  • The third check is an old case run again: the cap must not touch orders below it. In the real suite all part 1 tests run after this change too.

Example 2 · Coupons: the new tests and the code they asked for

CouponCycle.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Map;
class DiscountWithCoupons {                                     // before the rule change in the next section    static final BigDecimal MAX_DISCOUNT = new BigDecimal("500.00");    private final Map<String, BigDecimal> coupons;
    DiscountWithCoupons(Map<String, BigDecimal> coupons) {        this.coupons = coupons;    }
    BigDecimal discount(BigDecimal subtotal, boolean member, String coupon) {        BigDecimal sale = new BigDecimal("0.00");        if (subtotal.compareTo(new BigDecimal("1000.00")) >= 0) {            BigDecimal rate = member ? new BigDecimal("0.15") : new BigDecimal("0.10");            sale = subtotal.multiply(rate).setScale(2, RoundingMode.HALF_UP);        }        return sale.add(couponValue(coupon)).min(MAX_DISCOUNT).min(subtotal);    }
    BigDecimal couponValue(String code) {        if (code == null) return new BigDecimal("0.00");        BigDecimal value = coupons.get(code);        if (value == null) throw new IllegalArgumentException("Unknown coupon: " + code);        return value;    }}
public class CouponCycle {    static void check(String name, String expected, BigDecimal actual) {        if (new BigDecimal(expected).equals(actual)) {            System.out.println("PASS " + name);        } else {            System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);        }    }
    public static void main(String[] args) {        DiscountWithCoupons calc = new DiscountWithCoupons(                Map.of("FLAT100", new BigDecimal("100.00"), "WELCOME50", new BigDecimal("50.00")));
        check("coupon adds to the sale", "300.00", calc.discount(new BigDecimal("2000.00"), false, "FLAT100"));        check("coupon plus sale is capped", "500.00", calc.discount(new BigDecimal("3000.00"), true, "FLAT100"));        check("never more than the order", "60.00", calc.discount(new BigDecimal("60.00"), false, "FLAT100"));        check("coupon works without the sale", "50.00", calc.discount(new BigDecimal("400.00"), false, "WELCOME50"));        try {            calc.discount(new BigDecimal("2000.00"), false, "DIWALI");            System.out.println("FAIL unknown coupon is rejected: nothing thrown");        } catch (IllegalArgumentException e) {            System.out.println("PASS unknown coupon is rejected: " + e.getMessage());        }    }}
Output
PASS coupon adds to the sale
PASS coupon plus sale is capped
PASS never more than the order
PASS coupon works without the sale
PASS unknown coupon is rejected: Unknown coupon: DIWALI

What this code does

  • The coupon list arrives through the constructor because the first coupon test needed a way to say which codes exist. The tests chose that design: no hard-coded codes inside the calculator.
  • "Never more than the order" added the second limit, min(subtotal); without that test a Rs 60 order would get Rs 100 off. The unknown-coupon test made the code throw instead of silently ignoring a typo.

Cap: the total discount on one order is at most Rs 500.00. Coupon codes: a code such as FLAT100 takes a fixed Rs 100.00 off, on top of the sale discount. An unknown code is an error (Unknown coupon: DIWALI), and the discount is never more than the order itself, so a Rs 60 order with FLAT100 gets Rs 60 off.

Then the usual cycle: one red test, the simplest green, refactor.

Changing rules: let a failing test show what broke

A rule change is a new business rule that replaces an old one. In TDD you change the old rule's test first, watch it go red, then change the code until every test is green.

Members now get their 5% bonus at any order value. First change the old test, then try two code changes: a careless one and a correct one.

Example 3 · A rule change: the tests show what each attempt breaks

RuleChangeDemo.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Map;
import java.util.LinkedHashMap;import java.util.List;import java.util.function.BiFunction;
public class RuleChangeDemo {    record Case(String name, String subtotal, boolean member, String expected) {    }
    static BigDecimal pct(BigDecimal amount, String rate) {        return amount.multiply(new BigDecimal(rate)).setScale(2, RoundingMode.HALF_UP);    }
    static final BigDecimal MIN = new BigDecimal("1000.00");
    // Old rule: the member bonus also needs Rs 1000    static BigDecimal old(BigDecimal s, boolean m) {        return s.compareTo(MIN) < 0 ? new BigDecimal("0.00") : pct(s, m ? "0.15" : "0.10");    }
    // Careless change: just drop the minimum check    static BigDecimal careless(BigDecimal s, boolean m) {        return pct(s, m ? "0.15" : "0.10");    }
    // Correct change: the 10% needs Rs 1000, the 5% bonus does not    static BigDecimal correct(BigDecimal s, boolean m) {        BigDecimal rate = (s.compareTo(MIN) >= 0 ? new BigDecimal("0.10") : BigDecimal.ZERO)                .add(m ? new BigDecimal("0.05") : BigDecimal.ZERO);        return s.multiply(rate).setScale(2, RoundingMode.HALF_UP);    }
    public static void main(String[] args) {        List<Case> tests = List.of(                new Case("below 1000, no member", "999.99", false, "0.00"),                new Case("from 1000: 10%", "1000.00", false, "100.00"),                new Case("members get 15%", "2000.00", true, "300.00"),                new Case("members below 1000 still get 5% (NEW)", "999.99", true, "50.00"));
        LinkedHashMap<String, BiFunction<BigDecimal, Boolean, BigDecimal>> versions = new LinkedHashMap<>();        versions.put("old code", RuleChangeDemo::old);        versions.put("careless", RuleChangeDemo::careless);        versions.put("correct", RuleChangeDemo::correct);
        versions.forEach((label, version) -> {            System.out.println("-- " + label);            for (Case t : tests) {                BigDecimal actual = version.apply(new BigDecimal(t.subtotal()), t.member());                if (!new BigDecimal(t.expected()).equals(actual)) {                    System.out.println("   FAIL " + t.name() + ": expected " + t.expected() + " but was " + actual);                }            }        });    }}
Output
-- old code
   FAIL members below 1000 still get 5% (NEW): expected 50.00 but was 0.00
-- careless
   FAIL below 1000, no member: expected 0.00 but was 100.00
   FAIL members below 1000 still get 5% (NEW): expected 50.00 but was 150.00
-- correct

What this code does

  • Step one was changing the test, not the code: the updated test is the only red one against the old code. That red line is the rule change, written down.
  • Deleting the minimum check looks like the fix, but two tests go red and say why: non-members below Rs 1000 suddenly get 10%, and members get 15% instead of 5%. The correct version prints no failures at all.

The old test "members below Rs 1000 get nothing" becomes "members below Rs 1000 still get 5%" (999.99 → 50.00). Only after that test is red do you touch the code.

Find the bug

Find the line that breaks a rule

Tap the line of code that breaks the rule.

Rule: orders from Rs 1000.00 get the sale discount.

Round 1 of 3

Parameterised tests for the rule table

A rule table lists every case of a rule set as one row: the inputs and the expected result. In JUnit 5 it is a @ParameterizedTest with @CsvSource.

The cases so far are rows of the same table: subtotal, member, coupon and expected discount. The next example holds them in one test method, one row per case.

Example 4 · The rule table as a JUnit 5 parameterised test

Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/pricing)

Java
package com.shoplite.pricing;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;import java.util.Map;
import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;
class DiscountCalculatorTest {
    private final DiscountCalculator calculator = new DiscountCalculator(            Map.of("FLAT100", new BigDecimal("100.00"), "WELCOME50", new BigDecimal("50.00")));
    @ParameterizedTest(name = "{0}, member {1}, coupon {2} -> {3}")    @CsvSource({            "999.99,  false, ,          0.00",            "1000.00, false, ,          100.00",            "2499.50, false, ,          249.95",            // member bonus (any order value)            "2000.00, true,  ,          300.00",            "999.99,  true,  ,          50.00",            // cap            "6000.00, true,  ,          500.00",            // coupons            "2000.00, false, FLAT100,   300.00",            "3000.00, true,  FLAT100,   500.00",            "60.00,   false, FLAT100,   60.00",            "400.00,  false, WELCOME50, 50.00"    })    void discountFollowsTheRuleTable(BigDecimal subtotal, boolean member, String coupon, BigDecimal expected) {        assertThat(calculator.discount(subtotal, member, coupon)).isEqualTo(expected);    }
    @Test    void anUnknownCouponIsRejected() {        assertThatThrownBy(() -> calculator.discount(new BigDecimal("2000.00"), false, "DIWALI"))                .isInstanceOf(IllegalArgumentException.class)                .hasMessage("Unknown coupon: DIWALI");    }}
Sample output
DiscountCalculatorTest
  discountFollowsTheRuleTable(BigDecimal, boolean, String, BigDecimal)
    999.99, member false, coupon null -> 0.00
    1000.00, member false, coupon null -> 100.00
    2499.50, member false, coupon null -> 249.95
    2000.00, member true, coupon null -> 300.00
    999.99, member true, coupon null -> 50.00
    6000.00, member true, coupon null -> 500.00
    2000.00, member false, coupon FLAT100 -> 300.00
    3000.00, member true, coupon FLAT100 -> 500.00
    60.00, member false, coupon FLAT100 -> 60.00
    400.00, member false, coupon WELCOME50 -> 50.00
  anUnknownCouponIsRejected()
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.096 s -- in com.shoplite.pricing.DiscountCalculatorTest

What this code does

  • Every rule of both parts is one or two rows, grouped with comments. An empty CSV column becomes null, so "no coupon" needs no special value. The error case stays a separate test because it throws instead of returning a number.
  • The display names repeat the inputs, so a failing row reads like 999.99, member true, coupon null -> 50.00 in the report: enough to know which rule broke.

Keep error cases as separate tests (an unknown coupon throws, it does not return a number), and group the rows by rule with a short comment, so a reviewer can check the table against the business rules line by line.

Reviewing the final design the tests shaped

Constructor injection means giving a class what it needs, such as the list of coupons, through its constructor instead of hard-coding it inside. Tests can then pass their own values.

The finished calculator is small because the tests asked only for what the rules need. Here it is, with its whole rule table running against it.

Example 5 · The final calculator and its whole rule table

DiscountKataFinal.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Map;
/** ShopLite's festival discount: 10% from Rs 1000, +5% for members, coupons, capped at Rs 500. */class DiscountCalculator {    static final BigDecimal MIN_ORDER = new BigDecimal("1000.00");    static final BigDecimal SALE_RATE = new BigDecimal("0.10");    static final BigDecimal MEMBER_BONUS = new BigDecimal("0.05");    static final BigDecimal MAX_DISCOUNT = new BigDecimal("500.00");    static final BigDecimal NONE = new BigDecimal("0.00");
    private final Map<String, BigDecimal> coupons;
    DiscountCalculator(Map<String, BigDecimal> coupons) {        this.coupons = Map.copyOf(coupons);    }
    BigDecimal discount(BigDecimal subtotal, boolean member, String couponCode) {        BigDecimal total = percentOf(subtotal, rateFor(subtotal, member)).add(couponValue(couponCode));        return total.min(MAX_DISCOUNT).min(subtotal).setScale(2, RoundingMode.HALF_UP);    }
    private BigDecimal rateFor(BigDecimal subtotal, boolean member) {        BigDecimal rate = qualifiesForSale(subtotal) ? SALE_RATE : BigDecimal.ZERO;        return member ? rate.add(MEMBER_BONUS) : rate;    }
    private BigDecimal couponValue(String code) {        if (code == null || code.isBlank()) {            return NONE;        }        BigDecimal value = coupons.get(code);        if (value == null) {            throw new IllegalArgumentException("Unknown coupon: " + code);        }        return value;    }
    private static boolean qualifiesForSale(BigDecimal subtotal) {        return subtotal.compareTo(MIN_ORDER) >= 0;    }
    private static BigDecimal percentOf(BigDecimal amount, BigDecimal rate) {        return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP);    }}
public class DiscountKataFinal {    public static void main(String[] args) {        DiscountCalculator calc = new DiscountCalculator(                Map.of("FLAT100", new BigDecimal("100.00"), "WELCOME50", new BigDecimal("50.00")));
        String[][] table = {                {"999.99", "false", null, "0.00"},                {"1000.00", "false", null, "100.00"},                {"2499.50", "false", null, "249.95"},                {"2000.00", "true", null, "300.00"},                {"999.99", "true", null, "50.00"},                {"6000.00", "true", null, "500.00"},                {"2000.00", "false", "FLAT100", "300.00"},                {"3000.00", "true", "FLAT100", "500.00"},                {"60.00", "false", "FLAT100", "60.00"},                {"400.00", "false", "WELCOME50", "50.00"},        };        int passed = 0;        for (String[] row : table) {            BigDecimal actual = calc.discount(new BigDecimal(row[0]), Boolean.parseBoolean(row[1]), row[2]);            if (new BigDecimal(row[3]).equals(actual)) {                passed++;            } else {                System.out.println("FAIL " + String.join(", ", String.valueOf(row[0]), row[1], String.valueOf(row[2]))                        + ": expected " + row[3] + " but was " + actual);            }        }        System.out.println(passed + " of " + table.length + " rule rows pass");    }}
Output
10 of 10 rule rows pass

What this code does

  • The whole design fits on one screen: discount adds the percentage and the coupon and applies the two limits; rateFor and couponValue hold one family of rules each; constants name every number.
  • The coupon list comes in through the constructor (Map.copyOf keeps it read-only), so tests and the app can pass different codes. In shoplite-api the app would load them from the database; the calculator does not care where they come from.

The tests also shaped decisions you might otherwise skip: rounding once, two decimals in every result, and an exception for an unknown coupon instead of silently ignoring it. Each of those is now a test that fails if someone changes it by accident.

Next step

Check your understanding

10 quick questions