Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 119 ยท Testing

Test-Driven Development

Learn test-driven development in Java by building a ticket pricer test-first with JUnit, step by step through red, green and refactor, plus TDD's real benefits and limits.

So far you have written tests for code that already existed. Test-driven development (TDD) flips the order: you write a small failing test first, then just enough code to make it pass, then clean up. Repeat, in cycles of a few minutes each. The tests stop being an afterthought and become the tool you design with.

TDD was popularized by Kent Beck around 2000 as part of Extreme Programming, and it is still one of the most debated practices in software. In this lesson you will build a small class completely test-first, cycle by cycle, using JUnit and the techniques from Unit Testing with JUnit 6 and Parameterized Tests. Then you will look honestly at what TDD buys you, what it costs, and where it does not fit.

The cycle: red, green, refactor

Every TDD cycle has three steps:

  1. Red. Write one small test for behavior that does not exist yet. Run it and watch it fail. A failure proves the test can detect the missing behavior; a test you never saw fail might be testing nothing.
  2. Green. Write the simplest code that makes the test pass. Not the most elegant code, not the most general: the simplest. Ugly is allowed for a minute.
  3. Refactor. With all tests green, improve the design of both the production code and the tests: remove duplication, rename, extract methods. Run the tests after every change. The behavior must not change during this step.

Then pick the next behavior and go around again. Each loop should take minutes, not hours. If you have been red for longer than about ten minutes, the step was too big: revert to green and take a smaller one.

In Java, a test that does not compile counts as red too. In practice you write the test, let the IDE create the missing class and method with an empty body (returning 0 or null), and then run the test to see a real assertion failure.

The task: a cinema ticket pricer

A cinema wants a class that prices tickets. Before writing anything, write a test list: the behaviors you know about, in plain words. It is your to-do list for the session, and it grows as you discover cases.

TEXT
Test list
[ ] an adult ticket costs $12.00
[ ] children under 12 pay $7.00
[ ] seniors aged 65 and over pay $8.00
[ ] a 3D screening adds $3.00 to any ticket
[ ] on Tuesdays the base price is 25% off (the 3D surcharge is not discounted)
[ ] an age below 0 or above 120 is rejected

Prices are in cents (int) to avoid floating-point surprises. Pick the simplest item first: the adult price.

Cycle 1: the first red

The test describes how you want to use the class: new TicketPricer().price(30) should return 1200. The class does not exist yet, so we create the smallest version that compiles, returning 0. Run it:

Java Cycle 1: red

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Red, with exactly the message you would hope for: expected: <1200> but was: <0>. Now make it green with the simplest possible change. Edit the method to return 1200; and run again.

Returning a constant feels like cheating, and that is the point. Beck calls it Fake it: get to green fast, then let the next test force the real logic. When the implementation is obvious and small, you can skip the fake and write it directly (Obvious implementation). When you are unsure, add a second example that the fake cannot satisfy (Triangulation).

Cycles 2 to 4: triangulating the age rules

The next test, "children under 12 pay 700", breaks the constant. The simplest green is an if. Then the senior rule adds another branch. Each new rule comes with a boundary test, because off-by-one errors live exactly at 11/12 and 64/65. A parameterized test keeps the age table readable.

After three more red-green-refactor loops, the code and tests look like this:

Java Cycles 2-4: green on the age rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What happened along the way:

  • Cycle 2 added the row 11, 700. Red (was: <1200>). Green: if (age < 12) return 700;.
  • Then the row 12, 1200 was added to pin the boundary. It passed immediately. That is fine: a test that passes at once is still valuable when it documents a boundary, but it tells you the step added no new behavior.
  • Cycle 3 added 65, 800. Red. Green: the senior branch. The row 64, 1200 pinned the other boundary.
  • Refactor: the separate @Test methods written so far were merged into one @CsvSource table. Refactoring applies to test code too.

Try breaking it: change age >= 65 to age > 65 and run. The age 65 pays 800 row goes red and tells you precisely which boundary moved.

Cycle 5 and 6: a new requirement changes the design

The 3D surcharge and the Tuesday discount do not depend on the person; they depend on the screening. Writing the next test makes the design problem visible: price(30) has nowhere to put "3D" or "Tuesday". The test is the first user of your API, so this is where TDD gives design feedback, before any code relies on the wrong shape.

The tests drive a new signature, price(int age, Screening screening), with a record for the screening. The date is a parameter, not LocalDate.now(), so the tests can choose a Tuesday (see Test Doubles and Mockito for why). In the refactor step, the age rules move into a small basePrice method, so the remaining code reads like the business rules.

Java Cycles 5-6: 3D and Tuesdays, after refactoring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The test tuesdayDiscountDoesNotApplyToTheSurcharge is the interesting one. A first attempt that discounted the total ((base + 300) * 3 / 4 = 1125) would have passed every other test. Only an example that combines both rules catches it. When a requirement says "X except Y", write a test for the combination.

Also note the two helper factories Screening.regular(...) and Screening.in3d(...). They were extracted during a refactor step because the tests kept repeating new Screening(date, false). Making tests pleasant to write is part of the job.

Fixing a bug test-first

The last item on the list is input validation, and it arrives the way many requirements do: as a bug report. "The kiosk sold a child ticket for age -3." The TDD rule for bugs is simple: first write a test that reproduces the bug and fails, then fix it. The test proves you understood the bug, proves the fix works, and stops the bug from ever returning.

Java Reproducing a bug before fixing it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Run it: the three rejectsImpossibleAges rows fail with Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown., while the two boundary rows already pass. Now make them green by adding a guard at the top of price:

Java
if (age < 0 || age > 120) {
    throw new IllegalArgumentException("age must be between 0 and 120, was " + age);
}

Every item on the test list is done, and the finished class arrived with a complete, readable specification of itself.

What TDD gives you

  • A safety net from the first minute. Every behavior has a test, written when the behavior was fresh in your mind. Refactoring becomes routine instead of risky.
  • Design feedback. The test is the first client of your API. Awkward tests (huge setup, many mocks, no way to pass the date in) reveal awkward design while it is still cheap to change. The Screening record came directly from that pressure.
  • Small steps and focus. You are never more than a few minutes from green, so you rarely sit in a broken state wondering what you changed. The test list keeps scope under control.
  • Living documentation. A test table like "age 64 pays 1200, age 65 pays 800" states the rules more precisely than most specifications, and it cannot go out of date without turning red.
  • Testable code by construction. Code written to satisfy tests is, by definition, easy to test: dependencies are injected and side effects are isolated.

Limits and honest criticism

TDD is a tool, not a religion. Its critics make fair points:

  • It does not design the architecture for you. TDD shapes classes and methods well; it says little about service boundaries, data models or performance. Those still need thinking up front.
  • It is a poor fit for exploration. When you do not know what the solution looks like (a new library, a prototype, a tricky algorithm), write a throwaway spike without tests, learn from it, then delete it and rebuild test-first.
  • UI, layout and visual work are hard to drive with unit tests. Test the logic behind the UI and leave the rest to other kinds of testing.
  • Mock-heavy TDD can backfire. The "London" or outside-in style drives designs from the top with mocks for every collaborator; done carelessly, it produces tests that mirror the implementation and break on every refactor. The "Chicago" or classic style prefers real objects and state checks. Most teams mix them.
  • It costs time up front. Studies on productivity are mixed. Teams usually report fewer defects and easier changes later, paid for with slower first drafts.
  • Unit tests are not enough. TDD'd units can still be wired together wrongly. You still need the integration tests from the next lesson.

For existing code without tests, start with characterization tests: tests that record what the code does today, right or wrong, so you can refactor safely before changing behavior.

Common mistakes

  • Taking big steps. Writing five tests and then the whole implementation is "test-first", but you lose the fast feedback that makes TDD work. One test, one change.
  • Skipping refactor. Red-green-red-green without cleanup leaves the code as a pile of special cases. The refactor step is where the design improves.
  • Never seeing red. If a new test passes immediately, ask why. Either the behavior already existed (fine, but no new code is needed) or the test is broken.
  • Testing private methods. Test behavior through the public API. If a private method seems to need its own tests, it probably wants to be a separate class.
  • Gold-plating during green. Adding features no test asked for ("I'll need a discount for students later") puts untested code into the class. Add it to the test list instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of watching a new test fail before writing the code?

    A test you never saw fail might pass for the wrong reason, for example because it asserts on the wrong object. Red first shows that the test is wired to the behavior.
  2. 2. After the test assertEquals(1200, pricer.price(30)), a developer writes return 1200;. What is this technique called, and what comes next?

    Returning a constant gets to green quickly. Additional examples (triangulation) then make the constant impossible and drive the general code.
  3. 3. With the Tuesday rule implemented as (base + 300) * 3 / 4, which test catches the mistake?

    Only the combination exposes it: 1200 base on a Tuesday in 3D should be 900 + 300 = 1200, but the buggy formula gives 1125. The single-rule tests all still pass.
  4. 4. You receive a bug report. What does TDD tell you to do first?

    A failing reproduction test proves you understand the bug, shows when the fix works and prevents the bug from returning.
  5. 5. When is TDD a poor fit?

    For exploration, write a throwaway spike to learn, then rebuild the real code test-first.

Summary

  • TDD repeats a short cycle: red (a failing test), green (the simplest code that passes), refactor (clean up with tests green).
  • Start with a test list; pick the simplest item; take small steps; revert if you stay red too long.
  • Techniques: fake it, triangulation with a second example, obvious implementation when the code is trivial. Test boundaries and combinations of rules.
  • Tests are the first client of your API, so awkward tests signal awkward design. Inject time and other inputs.
  • For bugs, write a failing reproduction test first, then fix.
  • TDD gives a safety net, design feedback and living documentation; it does not replace architecture work, exploration spikes or integration tests.

Next: Integration Testing, where your tests talk to a real database and a real HTTP server.