JAVA-220 · Lesson 6 of 12 · 21 min
Test-driven development
▶ Video coming soon A video version of this lesson is on the way.
After reading week, on Thursday, October 21, Odile came to the session with a task of her own. Second Gear's rental prices had grown into a page of handwritten rules: 25 dollars a day for a city bike, 40 for the cargo bike, 45 for the tandem, and for rentals of a week or more, only five days charged out of every seven. ShopBook still charged every day at the same rate. Ingrid proposed that Hamza write the new price calculator test-first, one rule at a time, with Odile reading the tests to confirm each rule as it went in. "If the tests read like your price sheet," Ingrid told Odile, "you can check them without reading any Java."
Test first
Test-driven development, or TDD, is a way of writing code in which you write a failing test before the code that makes it pass. It was popularized by Kent Beck in the early 2000s as part of Extreme Programming, and it has three steps that repeat in a tight loop, often every few minutes.
- Red: write one small test for behavior that does not exist yet, run it and watch it fail.
- Green: write the simplest code that makes the test pass, even if it looks silly.
- Refactor: with all tests passing, improve the code and the tests, removing duplication and improving names, running the tests after each change.
Watching the test fail first is not a ritual. It proves the test can fail: a test that passes before the code exists is checking nothing, perhaps because it calls the wrong method or its assertion is missing. The green step's "simplest code" can be absurdly simple, such as returning a constant, because the next test will force it to become general. That discipline keeps every line of code justified by a test.
A worked example: rental prices
Hamza started with the plainest rule on Odile's sheet. Each step below is a complete program with its tests in main, run exactly as shown, so you can see the code and the tests move forward together.
public class Main {
static long price(String bike, int days) {
return 0;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
System.out.println("Step 1 (red): one test, no real code");
check("city bike for 1 day", 2500, price("CITY", 1));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Step 1 (red): one test, no real code FAIL city bike for 1 day: expected 2500 but was 0 RED
What this code does
The first test says a city bike for one day costs 2500 cents, and price is only a stub that returns 0, so the test fails and the run is red. That failure is the point of the step: it shows the test is wired up and really checks the result. Nothing more is written until the test has been seen to fail.
public class Main {
static long price(String bike, int days) {
return 2500;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
System.out.println("Step 2 (green): the simplest code that passes");
check("city bike for 1 day", 2500, price("CITY", 1));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Step 2 (green): the simplest code that passes PASS city bike for 1 day GREEN
What this code does
Returning the constant 2500 is the simplest change that turns the test green, and TDD deliberately allows it. The code is obviously incomplete, but now there is a passing test to protect it while it grows. The next tests will make a constant impossible.
Kent Beck called this move fake it till you make it. It feels wrong to experienced programmers, but it keeps steps tiny and makes the next test the reason for the next piece of logic. Adding tests that a constant cannot satisfy, such as three days or a different bike, is called triangulation: each new example narrows the code toward the general rule.
public class Main {
static long price(String bike, int days) {
long perDay = switch (bike) {
case "CARGO" -> 4000;
case "TANDEM" -> 4500;
default -> 2500;
};
return perDay * days;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
System.out.println("Step 3 (green): more tests forced the general rule");
check("city bike for 1 day", 2500, price("CITY", 1));
check("city bike for 3 days", 7500, price("CITY", 3));
check("cargo bike for 2 days", 8000, price("CARGO", 2));
check("tandem for 1 day", 4500, price("TANDEM", 1));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Step 3 (green): more tests forced the general rule PASS city bike for 1 day PASS city bike for 3 days PASS cargo bike for 2 days PASS tandem for 1 day GREEN
What this code does
Three new tests, for three days and for the other two bikes, can no longer be passed by a constant, so the code grows a rate for each bike multiplied by the number of days. All four tests pass, and each test reads like a line of Odile's price sheet. The default branch charges the city rate for any unknown bike, a weakness the refactor step will remove.
With everything green, Hamza could refactor, but first he added the weekly rule, again test-first. Odile read the new tests and caught something at once: "Nine days is one week and two days, so five plus two, seven days charged. Is that what your test says?" It was: 7 times 25 dollars is 175 dollars, 17500 cents.
public class Main {
static long price(String bike, int days) {
long perDay = switch (bike) {
case "CARGO" -> 4000;
case "TANDEM" -> 4500;
default -> 2500;
};
return perDay * days;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
System.out.println("Step 4 (red): a new rule, weekly rentals charge only 5 days per 7");
check("city bike for 3 days", 7500, price("CITY", 3));
check("cargo bike for 2 days", 8000, price("CARGO", 2));
check("city bike for 7 days", 12500, price("CITY", 7));
check("city bike for 9 days", 17500, price("CITY", 9));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Step 4 (red): a new rule, weekly rentals charge only 5 days per 7 PASS city bike for 3 days PASS cargo bike for 2 days FAIL city bike for 7 days: expected 12500 but was 17500 FAIL city bike for 9 days: expected 17500 but was 22500 RED
What this code does
Two new tests describe the weekly rule: seven days should cost five days' rent and nine days should cost seven. The old code charges every day, so both new tests fail while the earlier ones still pass, and the run is red again. The failure messages, 17500 expected against 22500 actual, show exactly how far the code is from the rule.
public class Main {
enum Bike {
CITY(2500), CARGO(4000), TANDEM(4500);
final long perDayCents;
Bike(long perDayCents) { this.perDayCents = perDayCents; }
}
static int chargedDays(int days) {
int weeks = days / 7;
return weeks * 5 + days % 7;
}
static long price(Bike bike, int days) {
return bike.perDayCents * chargedDays(days);
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
System.out.println("Step 5 (green, then refactored): weekly rule, and an enum instead of strings");
check("city bike for 3 days", 7500, price(Bike.CITY, 3));
check("cargo bike for 2 days", 8000, price(Bike.CARGO, 2));
check("city bike for 7 days", 12500, price(Bike.CITY, 7));
check("city bike for 9 days", 17500, price(Bike.CITY, 9));
check("tandem for 14 days", 45000, price(Bike.TANDEM, 14));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Step 5 (green, then refactored): weekly rule, and an enum instead of strings PASS city bike for 3 days PASS cargo bike for 2 days PASS city bike for 7 days PASS city bike for 9 days PASS tandem for 14 days GREEN
What this code does
chargedDays counts five days for each full week plus the leftover days, which makes all the weekly tests pass, including a new fourteen-day tandem test. Then, with everything green, the refactor step replaced the bike name strings with an enum, so an unknown bike name can no longer slip through to the city rate. The tests were updated to use the enum and still all pass, which is the evidence that the refactor did not change any price.
Five small steps, each a few minutes, produced a calculator with five tests that describe every rule, and a design improved twice without fear. Odile signed off by reading the test names, not the code. That is one of the quieter benefits of TDD: tests written first are written from the point of view of the person who uses the code.
Why TDD helps
| Benefit | Why it happens |
|---|---|
| Every line of code is covered by a test | No code is written except to make a failing test pass |
| Better design | Code written to be tested first tends to have small methods, clear inputs and few hidden dependencies |
| Fast feedback | Problems appear seconds after they are introduced, in the few lines just written |
| Living documentation | Tests describe each rule in examples a non-programmer can read |
| Safe refactoring | A complete set of tests is in place before any cleanup |
TDD has costs and critics too. Writing tests first is slower at the start, and it fits some problems better than others. It shines for logic with clear rules, such as prices, reorder levels and date calculations. It is awkward for exploratory work, such as trying out a new library or designing a user interface, where you do not yet know what the behavior should be; many developers explore first, throw the experiment away, and then build the real code test-first.
Good habits for test-first work
- Take small steps: one behavior per test, and run the tests after every change.
- Keep a list of tests still to write, so new ideas do not interrupt the current step.
- Never refactor while a test is red; get back to green first.
- Refactor the tests too: duplicated setup belongs in a builder or @BeforeEach.
- Commit to version control at every green step, so a bad experiment can be undone in seconds.
Hamza's test list for the calculator, kept on a sticky note, still had two items when the session ended: a late fee for bikes returned after the due date, and a rule Odile was not sure about, a discount for youth program members. The second one he wrote as a question for Odile rather than as a test, because a test should describe a decision that has been made, not guess at one.
Try it yourself
Red to green: a late fee
Odile's sheet says a bike returned late costs 1000 cents for each day late, and nothing if returned on time or early. The tests are written; lateFee is only a stub, so the run is red.
Make the tests pass with the simplest correct code. The program should print three PASS lines and then GREEN.
public class Main {
static long lateFee(int daysLate) {
return 0;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
check("on time", 0, lateFee(0));
check("one day late", 1000, lateFee(1));
check("returned two days early", 0, lateFee(-2));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Try it yourself
Write the next test first
The weekly rule is implemented. Odile adds a rule: a rental of 0 days is not allowed, and chargedDays should return -1 to signal it. Write the test first: add a check call for 0 days expecting -1, see it fail, then change chargedDays so every test passes.
The program should print four PASS lines and then GREEN.
public class Main {
static int chargedDays(int days) {
return days / 7 * 5 + days % 7;
}
static int failed = 0;
static void check(String name, long expected, long actual) {
if (expected == actual) System.out.println(" PASS " + name);
else { failed++; System.out.println(" FAIL " + name + ": expected " + expected + " but was " + actual); }
}
public static void main(String[] args) {
check("3 days", 3, chargedDays(3));
check("7 days", 5, chargedDays(7));
check("9 days", 7, chargedDays(9));
System.out.println(failed == 0 ? "GREEN" : "RED");
}
}Common mistakes
MistakeWriting the code first and the test afterwards, and calling it TDD.
InsteadWrite the failing test first and watch it fail; that proves the test checks something.
MistakeTaking big steps that need many lines of code to pass.
InsteadWrite one small test at a time and the least code that passes it.
MistakeRefactoring while tests are failing.
InsteadGet back to green first, then refactor, running the tests after each change.
MistakeNever refactoring once tests pass.
InsteadUse the green state to improve names and remove duplication, in code and tests.
MistakeWriting tests that guess at undecided rules.
InsteadAsk the person who owns the rule, and write the test once it is decided.
Summary and key terms
- Test-driven development writes a failing test before the code that makes it pass, in a loop of red, green and refactor.
- Seeing the test fail proves it can fail.
- The green step uses the simplest code that passes, even a constant, and further tests triangulate toward the general rule.
- Refactoring happens only when everything is green, and the tests confirm that behavior did not change.
- TDD gives complete test coverage of new code, simpler designs, fast feedback and tests that read as examples of each rule, at the cost of slower starts; it suits clear rules better than exploration.
- Small steps, a list of tests still to write and frequent commits keep the loop safe.
- Test-driven development (TDD)
- Writing a failing test before the code that makes it pass, in short repeated cycles.
- Red
- The TDD step of writing a test and watching it fail.
- Green
- The TDD step of writing the simplest code that makes the failing test pass.
- Refactor
- The TDD step of improving the design while all tests stay green.
- Fake it till you make it
- Passing a test with the simplest possible code, such as a constant, and letting later tests force the real logic.
- Triangulation
- Adding examples that a simple implementation cannot satisfy, driving the code to the general rule.
- Test list
- A running list of behaviors still to test, kept so new ideas do not interrupt the current step.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why watch a new test fail before making it pass?
Show answer
To prove the test can fail and really checks the behavior.
What is the green step allowed to do?
Show answer
Anything simple that passes, even returning a constant.
What is triangulation?
Show answer
Adding tests that force the simple code to become the general rule.
When may you refactor in TDD?
Show answer
Only when all tests pass, running them after each change.
Why did Hamza ask Odile about the youth discount instead of writing a test?
Show answer
A test should describe a decided rule, and that rule was not decided.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.