Red, green, refactor
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite works, but any change might break it, and nobody notices until a customer does. Writing the test before the code gives you a safety net from the first line. Here is the short rhythm that builds it.
Red: write a failing test first
TDD (test-driven development) is writing code in short cycles: a failing test first, then the simplest code that passes it, then a clean-up. Every line of code exists because a test asked for it.
Before any code exists, you write one small test for it and run it. The test must fail: that proves it can fail and that the behaviour is really missing.
Example 1 · Red: the first test fails
import java.math.BigDecimal;
public class RupeesRed { // Not written yet: only a stub, so the code compiles static String rupees(BigDecimal amount) { return null; }
static void check(String name, String expected, String actual) { if (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) { // Test list: zero, small amount, thousand, lakh, crore, rounding of paise check("zero", "Rs 0.00", String.valueOf(rupees(new BigDecimal("0")))); }}FAIL zero: expected Rs 0.00 but was null
What this code does
- The test decides the design: a static method
rupees(BigDecimal)that returns text. The stub only makes the program compile; the test is red, as it should be. - The comment holds the test list. Only the first, simplest case is turned into a test now.
The test is written from the caller's point of view, so it also designs the code: the method name, its parameters and its return type are decided before any implementation exists. For ShopLite's rupee formatter, the first test says that zero is shown as Rs 0.00.
The stub in the example only lets the program compile. Without it you would see a compile error, and a compile error proves nothing about behaviour.
Green: write just enough code to pass
Fake it means passing the first test with the simplest possible code, even a constant such as return "Rs 0.00";. The next test, with a different value, then forces the real code.
Now make the failing test pass with the simplest code that works, even if it looks silly. Here that is a constant.
Example 2 · Green: fake it
import java.math.BigDecimal;
public class RupeesGreen { static String rupees(BigDecimal amount) { return "Rs 0.00"; // the simplest code that passes the only test }
static void check(String name, String expected, String actual) { if (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("zero", "Rs 0.00", rupees(new BigDecimal("0"))); }}PASS zero
What this code does
- Returning a constant looks like cheating, but it is exactly right for now: one test, one passing answer. It also proves the test is wired to the method.
- The fake will not survive the next test. Waiting for a test to force the real code keeps every step small and every line covered.
Do not write code for tests you have not written yet. Every line of production code should exist because a failing test asked for it, so every line is covered by a test from the start.
Order of execution
The first green, step by step
Tap the steps in the order a TDD developer does them.
Refactor: clean up with the tests as a safety net
Refactor means changing the structure of working code, such as names, small methods and removed duplication, without changing what it does. It is done only while every test is green.
All six tests are green, but the first version of the formatter is one long method. Split it into small methods and run the tests after each move.
Example 3 · Refactor: same behaviour, clearer code
import java.math.BigDecimal;import java.math.RoundingMode;
public class RupeesRefactored { // Before the refactor this was one 20-line method with nested ifs. // Now: one method per idea, and every test still passes. static String rupees(BigDecimal amount) { String plain = amount.setScale(2, RoundingMode.HALF_UP).toPlainString(); int dot = plain.indexOf('.'); return "Rs " + groupIndian(plain.substring(0, dot)) + plain.substring(dot); }
// 1234567 -> 12,34,567: the last three digits, then groups of two static String groupIndian(String digits) { if (digits.length() <= 3) { return digits; } String rest = digits.substring(0, digits.length() - 3); String grouped = "," + digits.substring(digits.length() - 3); while (rest.length() > 2) { grouped = "," + rest.substring(rest.length() - 2) + grouped; rest = rest.substring(0, rest.length() - 2); } return rest + grouped; }
static void check(String name, String expected, String actual) { if (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("zero", "Rs 0.00", rupees(new BigDecimal("0"))); check("small amount", "Rs 999.00", rupees(new BigDecimal("999"))); check("one thousand", "Rs 1,000.00", rupees(new BigDecimal("1000"))); check("one lakh", "Rs 1,23,456.00", rupees(new BigDecimal("123456"))); check("one crore", "Rs 1,23,45,678.50", rupees(new BigDecimal("12345678.5"))); check("paise rounded half up", "Rs 17,999.01", rupees(new BigDecimal("17999.005"))); }}PASS zero PASS small amount PASS one thousand PASS one lakh PASS one crore PASS paise rounded half up
What this code does
- After all six tests were green, the long first version was split into
rupees(rounding and the two parts) andgroupIndian(the commas). The tests were run after each small move and stayed green. - That is the value of the safety net: you can reshape working code freely, because any mistake shows up as a FAIL line within a second.
Because every test is green before you start, you can run them after each small change. If one goes red, the last change broke something and is easy to undo.
Refactor the tests too: a helper for repeated set-up, a clearer name. Never add new behaviour in this step; new behaviour starts with a new red test.
Tiny steps, a test list and triangulation
Triangulation means adding a second test with a different value, so that no constant can pass both and you must write the general rule.
A second test with another value, 999 instead of 0, breaks the fake. Watch the fake and the general version run against the same checks.
Example 4 · Triangulation: a second example breaks the fake
import java.math.BigDecimal;import java.math.RoundingMode;
public class RupeesTriangulate { static String fake(BigDecimal amount) { return "Rs 0.00"; }
static String general(BigDecimal amount) { return "Rs " + amount.setScale(2, RoundingMode.HALF_UP).toPlainString(); }
static void check(String name, String expected, String actual) { if (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) { System.out.println("-- fake it"); check("zero", "Rs 0.00", fake(new BigDecimal("0"))); check("small amount", "Rs 999.00", fake(new BigDecimal("999")));
System.out.println("-- general rule"); check("zero", "Rs 0.00", general(new BigDecimal("0"))); check("small amount", "Rs 999.00", general(new BigDecimal("999"))); check("one thousand", "Rs 1,000.00", general(new BigDecimal("1000"))); }}-- fake it PASS zero FAIL small amount: expected Rs 999.00 but was Rs 0.00 -- general rule PASS zero PASS small amount FAIL one thousand: expected Rs 1,000.00 but was Rs 1000.00
What this code does
- The second test, 999, triangulates: no constant can satisfy both 0 and 999, so the code must become general (
setScale(2)andtoPlainString). - The general version passes both, and the next test on the list, one thousand, is red again: it forces the comma rule. Each test moves the code one small step.
Before coding, write a test list: the cases you can think of, simplest first. For the rupee formatter: zero, a small amount, one thousand, a lakh, a crore and the rounding of paise.
Work through the list one test at a time, and add new ideas to the list instead of coding them at once. Each new test should force exactly one small change in the code.
Predict the output
Predict the checks
Read the code and choose what the checks print.
Round 1 of 2
The general version after triangulation, with the next test from the list.
A single-file TDD demo with a hand-rolled check
A test list is a written list of the cases you plan to test, simplest first. You add new ideas to it as you think of them and turn one case at a time into a test.
A check(name, expected, actual) method and a main are enough to practise the cycle in one file. The replay runs one test list against each version of the formatter.
Example 5 · A TDD replay: each version against the growing test list
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.function.Function;
public class TddReplay { record Case(String name, String input, String expected) { }
static String comma(String digits) { // version 3: only the thousands comma return digits.length() <= 3 ? digits : digits.substring(0, digits.length() - 3) + "," + digits.substring(digits.length() - 3); }
static String indian(String digits) { // version 4: lakhs and crores too if (digits.length() <= 3) return digits; String rest = digits.substring(0, digits.length() - 3); String grouped = "," + digits.substring(digits.length() - 3); while (rest.length() > 2) { grouped = "," + rest.substring(rest.length() - 2) + grouped; rest = rest.substring(0, rest.length() - 2); } return rest + grouped; }
static Function<BigDecimal, String> withGrouping(Function<String, String> group) { return amount -> { String plain = amount.setScale(2, RoundingMode.HALF_UP).toPlainString(); int dot = plain.indexOf('.'); return "Rs " + group.apply(plain.substring(0, dot)) + plain.substring(dot); }; }
public static void main(String[] args) { List<Case> testList = List.of( new Case("zero", "0", "Rs 0.00"), new Case("small amount", "999", "Rs 999.00"), new Case("one thousand", "1000", "Rs 1,000.00"), new Case("one lakh", "123456", "Rs 1,23,456.00"));
Map<String, Function<BigDecimal, String>> versions = new LinkedHashMap<>(); versions.put("v1 fake it ", amount -> "Rs 0.00"); versions.put("v2 two decimals ", withGrouping(digits -> digits)); versions.put("v3 thousands ", withGrouping(TddReplay::comma)); versions.put("v4 Indian groups", withGrouping(TddReplay::indian));
for (Map.Entry<String, Function<BigDecimal, String>> version : versions.entrySet()) { StringBuilder line = new StringBuilder(version.getKey() + ":"); for (Case test : testList) { String actual = version.getValue().apply(new BigDecimal(test.input())); line.append(test.expected().equals(actual) ? " green" : " RED"); } System.out.println(line); } }}v1 fake it : green RED RED RED v2 two decimals : green green RED RED v3 thousands : green green green RED v4 Indian groups: green green green green
What this code does
- Each row is one version of the formatter run against the whole test list (zero, 999, one thousand, one lakh). The staircase of greens is the TDD rhythm: every version was written to turn exactly one more test green.
- v3 shows why the list matters: it puts one comma and gets
1,000.00right, but writes a lakh as123,456.00. The fourth test forced the Indian grouping rule.
Example 6 · The same tests in JUnit 5
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/common)
package com.shoplite.common;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;
class RupeesTest {
@ParameterizedTest(name = "{0} -> {1}") @CsvSource(delimiter = '|', value = { "0 | Rs 0.00", "999 | Rs 999.00", "1000 | Rs 1,000.00", "123456 | Rs 1,23,456.00", "12345678.5 | Rs 1,23,45,678.50", "17999.005 | Rs 17,999.01" }) void formatsInIndianStyle(BigDecimal amount, String expected) { assertEquals(expected, Rupees.format(amount)); }}[INFO] Running com.shoplite.common.RupeesTest [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.064 s -- in com.shoplite.common.RupeesTest
What this code does
- In a project the test list becomes a parameterised table, here with
|as the delimiter because the expected text contains commas. In TDD you add one row at a time, watch it fail, then make it pass. Rupees.formatis the refactored code from Example 3 moved intocom.shoplite.common.Rupees. The single-filecheckand JUnit play the same role: a fast, automatic answer after every small change.
In a project, the same checks become JUnit @Test methods: JUnit finds them, runs them all and prints a report. The cycle stays exactly the same.
Next step
Check your understanding
10 quick questions