TDD kata: a discount calculator, part 1
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's Diwali sale starts on Friday and the discount rules are agreed. Get one rule wrong and customers are over- or under-charged. Building the rules test-first, one small cycle at a time, keeps each rule safe.
The rules: percentage discount, minimum order value, member bonus
A kata is a small exercise you repeat to practise a skill, like net practice in cricket. A TDD kata builds a small piece of real logic test-first, one red-green-refactor cycle per rule.
ShopLite's Diwali sale has three rules: no discount below Rs 1000.00, 10% from Rs 1000.00, and 5% more for members. Each case becomes one line of the test list.
Test list: DiscountCalculator.discount(subtotal, member) [ ] 999.99, not a member -> 0.00 (no discount below the minimum) [ ] 1000.00, not a member -> 100.00 (exactly the minimum: 10%) [ ] 2499.50, not a member -> 249.95 (rounded to paise) [ ] 2000.00, member -> 300.00 (10% + 5%) [ ] 999.99, member -> 0.00 (bonus also needs the minimum)The rules in full. Minimum order value: orders below Rs 1000.00 get no discount. Percentage discount: from Rs 1000.00 the order gets 10% off its subtotal. Member bonus: ShopLite members get an extra 5%, so 15% in total, also only from Rs 1000.00. Discounts are rounded to paise, half up.
The list puts the edge cases next to each other (999.99 and 1000.00) and includes one rounding case.
Start with the simplest test: no discount
The simplest test is the test on the list that needs the least code to pass, such as a small order that gets no discount.
Start with a small order that gets no discount. Run it against a stub (red), then against a constant (green).
Example 1 · Cycle 1: the simplest test, red then green
import java.math.BigDecimal;import java.math.RoundingMode;
public class DiscountCycle1 { static BigDecimal discountStub(BigDecimal subtotal, boolean member) { return null; // red: nothing written yet }
static BigDecimal discount(BigDecimal subtotal, boolean member) { return new BigDecimal("0.00"); // green: fake it }
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: below Rs 1000 there is no discount", "0.00", discountStub(new BigDecimal("999.99"), false)); check("green: below Rs 1000 there is no discount", "0.00", discount(new BigDecimal("999.99"), false)); }}FAIL red: below Rs 1000 there is no discount: expected 0.00 but was null PASS green: below Rs 1000 there is no discount
What this code does
- Both versions are in one file so you can see the cycle: the stub fails the test (red), the constant passes it (green). In practice you edit the same method rather than keeping two.
- The test already pins down the design: a
BigDecimalresult with two decimals,0.00, not0ornull.
The green step is a constant. That feels too easy, but it is the point: the next test on the list makes the constant fail and asks for the first real rule.
Add one rule per cycle and keep every test green
A cycle is one red-green-refactor round for one test from the list: see it fail, make it pass, then clean up.
Take the next test from the list, watch it fail, and add only the code that rule needs. Below, the 10% rule and rounding come first, then the member bonus.
Example 2 · Cycle 2: the 10% rule and the minimum order value
import java.math.BigDecimal;import java.math.RoundingMode;
public class DiscountCycle2 { static BigDecimal discount(BigDecimal subtotal, boolean member) { if (subtotal.compareTo(new BigDecimal("1000.00")) < 0) { return new BigDecimal("0.00"); } return subtotal.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); }
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("below Rs 1000 there is no discount", "0.00", discount(new BigDecimal("999.99"), false)); check("from Rs 1000 the sale gives 10%", "100.00", discount(new BigDecimal("1000.00"), false)); check("10% is rounded to paise", "249.95", discount(new BigDecimal("2499.50"), false)); }}PASS below Rs 1000 there is no discount PASS from Rs 1000 the sale gives 10% PASS 10% is rounded to paise
What this code does
- The 1000.00 test failed against the constant, so this cycle added the minimum check and the 10% calculation. The first test still passes: the old rule survived the new code.
compareTohandles the boundary exactly: 999.99 is below, 1000.00 is not.setScale(2, HALF_UP)turns249.950into249.95with two decimals, which the third test pins down.
Example 3 · Cycle 3: the member test is red against the old code
import java.math.BigDecimal;import java.math.RoundingMode;
public class DiscountCycle3Red { static BigDecimal discount(BigDecimal subtotal, boolean member) { // unchanged from cycle 2 if (subtotal.compareTo(new BigDecimal("1000.00")) < 0) { return new BigDecimal("0.00"); } return subtotal.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); }
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("below Rs 1000 there is no discount", "0.00", discount(new BigDecimal("999.99"), false)); check("from Rs 1000 the sale gives 10%", "100.00", discount(new BigDecimal("1000.00"), false)); check("10% is rounded to paise", "249.95", discount(new BigDecimal("2499.50"), false)); check("members get 15%", "300.00", discount(new BigDecimal("2000.00"), true)); check("members below Rs 1000 get nothing", "0.00", discount(new BigDecimal("999.99"), true)); }}PASS below Rs 1000 there is no discount PASS from Rs 1000 the sale gives 10% PASS 10% is rounded to paise FAIL members get 15%: expected 300.00 but was 200.00 PASS members below Rs 1000 get nothing
What this code does
- The new member test fails with a clear reason: 200.00 is only the 10%. That is the red that asks for the bonus.
- The last test, "members below Rs 1000 get nothing", already passes. That is fine: it documents a rule the code happens to follow, and it will protect that rule when the bonus code is added.
Example 4 · Cycle 3 green: works, but repeats itself
import java.math.BigDecimal;import java.math.RoundingMode;
public class DiscountCycle3Green { static BigDecimal discount(BigDecimal subtotal, boolean member) { if (subtotal.compareTo(new BigDecimal("1000.00")) < 0) { return new BigDecimal("0.00"); } if (member) { return subtotal.multiply(new BigDecimal("0.10")).add(subtotal.multiply(new BigDecimal("0.05"))) .setScale(2, RoundingMode.HALF_UP); } return subtotal.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); }
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("below Rs 1000 there is no discount", "0.00", discount(new BigDecimal("999.99"), false)); check("from Rs 1000 the sale gives 10%", "100.00", discount(new BigDecimal("1000.00"), false)); check("10% is rounded to paise", "249.95", discount(new BigDecimal("2499.50"), false)); check("members get 15%", "300.00", discount(new BigDecimal("2000.00"), true)); check("members below Rs 1000 get nothing", "0.00", discount(new BigDecimal("999.99"), true)); }}PASS below Rs 1000 there is no discount PASS from Rs 1000 the sale gives 10% PASS 10% is rounded to paise PASS members get 15% PASS members below Rs 1000 get nothing
What this code does
- All five tests are green: the simplest change that passed was an
if (member)branch. Being green comes first; beauty comes in the next step. - Notice the smell:
multiply(new BigDecimal("0.10"))andsetScale(2, HALF_UP)appear twice, and the numbers have no names. That is exactly what the refactor step fixes.
After every change, all tests run, not just the new one. If an older test goes red, the new code broke an earlier rule, and you know within seconds instead of after release.
Refactor duplicated conditions into small methods
A magic number is a number written directly in code with no name, like 0.10 for the sale rate. A constant such as SALE_RATE shows what the number means.
With five green tests the code works, but it repeats itself and hides its numbers. Name the ideas as small methods and the numbers as constants.
Example 5 · Refactor: small methods, same five green tests
import java.math.BigDecimal;import java.math.RoundingMode;
public class DiscountRefactored { 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 NONE = new BigDecimal("0.00");
static BigDecimal discount(BigDecimal subtotal, boolean member) { if (!qualifiesForSale(subtotal)) { return NONE; } return percentOf(subtotal, rateFor(member)); }
static boolean qualifiesForSale(BigDecimal subtotal) { return subtotal.compareTo(MIN_ORDER) >= 0; }
static BigDecimal rateFor(boolean member) { return member ? SALE_RATE.add(MEMBER_BONUS) : SALE_RATE; }
static BigDecimal percentOf(BigDecimal amount, BigDecimal rate) { return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP); }
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("below Rs 1000 there is no discount", "0.00", discount(new BigDecimal("999.99"), false)); check("from Rs 1000 the sale gives 10%", "100.00", discount(new BigDecimal("1000.00"), false)); check("10% is rounded to paise", "249.95", discount(new BigDecimal("2499.50"), false)); check("members get 15%", "300.00", discount(new BigDecimal("2000.00"), true)); check("members below Rs 1000 get nothing", "0.00", discount(new BigDecimal("999.99"), true)); }}PASS below Rs 1000 there is no discount PASS from Rs 1000 the sale gives 10% PASS 10% is rounded to paise PASS members get 15% PASS members below Rs 1000 get nothing
What this code does
discountnow reads like the rules: if the order does not qualify, no discount; otherwise a percentage of the subtotal at the rate for this customer. Each idea has one method and each number one named constant.- The tests did not change and are still all green, which proves the refactor kept the behaviour. Rounding once, on the combined 15%, is also more correct than rounding two parts separately.
Example 6 · The kata's tests in JUnit 5
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/pricing)
package com.shoplite.pricing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
class DiscountCalculatorTest {
private final DiscountCalculator calculator = new DiscountCalculator();
@Test void belowTheMinimumThereIsNoDiscount() { assertEquals(new BigDecimal("0.00"), calculator.discount(new BigDecimal("999.99"), false)); }
@Test void fromTheMinimumTheSaleGivesTenPercent() { assertEquals(new BigDecimal("100.00"), calculator.discount(new BigDecimal("1000.00"), false)); }
@Test void theDiscountIsRoundedToPaise() { assertEquals(new BigDecimal("249.95"), calculator.discount(new BigDecimal("2499.50"), false)); }
@Test void membersGetFifteenPercent() { assertEquals(new BigDecimal("300.00"), calculator.discount(new BigDecimal("2000.00"), true)); }
@Test void membersBelowTheMinimumGetNothing() { assertEquals(new BigDecimal("0.00"), calculator.discount(new BigDecimal("999.99"), true)); }}[INFO] Running com.shoplite.pricing.DiscountCalculatorTest [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.047 s -- in com.shoplite.pricing.DiscountCalculatorTest
What this code does
- In
shoplite-apithe same five cases are five@Testmethods, and the calculator becomes a classcom.shoplite.pricing.DiscountCalculatorwith an instance method, so part 2 can give it coupon data. - In real TDD you write these JUnit tests one at a time, exactly in the cycle order shown above; part 2 turns them into a parameterised table.
Run the tests after each small move. The behaviour does not change, but the code now reads like the rules, so the new rules in part 2 are easy to add.
Fix the error
Fix the constants
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
The sale rate is named as a constant.
Error
SaleRules.java:4: error: incompatible types: double cannot be converted to BigDecimal
static final BigDecimal SALE_RATE = 0.10;
^Next step
Check your understanding
10 quick questions