Skip to lesson

When TDD helps and when it does not

ShopLite's team wants tests for everything, while a manager says TDD slows delivery. Both cannot be right. The answer depends on one question: do you know the expected result before you start?

Where TDD shines: business rules, bug fixes, pure logic

Pure logic is code with plain inputs and plain outputs: no screen, network or database. It is the easiest code to write test-first, and each test runs in milliseconds.

TDD works best when you can state the expected answer before writing the code: discount rules, validation, calculations. Here is a ShopLite cancellation rule written test-first.

Example 1 · A business rule written test-first reads like the requirement

CancellationRules.javaJava
import java.time.LocalDate;
class OrderCancellation {    enum Status { PLACED, SHIPPED, DELIVERED, CANCELLED }
    // Rule: a customer may cancel while the order is PLACED and at most 7 days after ordering    static boolean canCancel(Status status, LocalDate orderedOn, LocalDate today) {        return status == Status.PLACED && !today.isAfter(orderedOn.plusDays(7));    }}
public class CancellationRules {    static void check(String rule, boolean expected, boolean actual) {        System.out.println((expected == actual ? "PASS " : "FAIL ") + rule);    }
    public static void main(String[] args) {        LocalDate ordered = LocalDate.of(2026, 10, 1);        check("placed today can be cancelled", true,                OrderCancellation.canCancel(OrderCancellation.Status.PLACED, ordered, ordered));        check("placed, day 7 can still be cancelled", true,                OrderCancellation.canCancel(OrderCancellation.Status.PLACED, ordered, ordered.plusDays(7)));        check("placed, day 8 is too late", false,                OrderCancellation.canCancel(OrderCancellation.Status.PLACED, ordered, ordered.plusDays(8)));        check("shipped cannot be cancelled", false,                OrderCancellation.canCancel(OrderCancellation.Status.SHIPPED, ordered, ordered));    }}
Output
PASS placed today can be cancelled
PASS placed, day 7 can still be cancelled
PASS placed, day 8 is too late
PASS shipped cannot be cancelled

What this code does

  • Every test name is a sentence from the requirement, and every expected value was known before the code existed: the perfect ground for TDD. Day 7 and day 8 are the boundary pair.
  • today is a parameter instead of LocalDate.now(), a decision the tests forced: you cannot test "day 8" against the real calendar.

State changes such as "an order can be cancelled only while PLACED" are pure logic too. For such code the test list is almost the requirement itself, and writing the tests first catches misunderstandings early ("is day 7 still allowed?").

Where it struggles: UI layout, spikes and unknown APIs

A spike is a short, throw-away experiment to learn how something works, such as a new library or API, before you know what to assert.

When you cannot know the expected result in advance, explore first. This spike prints several date patterns to see what Java produces.

Example 2 · A spike: exploring an API before you know what to assert

FormatterSpike.javaJava
import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.Locale;
public class FormatterSpike {    // Throw-away exploration: which pattern prints an order time the way Indian customers expect?    public static void main(String[] args) {        LocalDateTime placed = LocalDateTime.of(2026, 10, 16, 18, 5);        String[] patterns = {"dd/MM/yyyy", "d MMM yyyy, h:mm a", "dd-MM-yy HH:mm", "EEEE, d MMMM"};        for (String pattern : patterns) {            String text = placed.format(DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH));            System.out.printf("%-20s -> %s%n", pattern, text);        }    }}
Output
dd/MM/yyyy           -> 16/10/2026
d MMM yyyy, h:mm a   -> 16 Oct 2026, 6:05 PM
dd-MM-yy HH:mm       -> 16-10-26 18:05
EEEE, d MMMM         -> Friday, 16 October

What this code does

  • This is not a test and should not be one yet: the point is to learn what the formatter can do. Before running it, you could not have written the expected values (for example, how the a pattern writes PM depends on the Locale you pass).
  • Once the team picks d MMM yyyy, h:mm a, the spike is thrown away and the real formatOrderTime method is written test-first, with the expected text now known.

UI layout (does the page look right on a phone?) is judged by eye, and unknown APIs often surprise you in ways no test list predicts.

The usual approach: explore in a spike, throw it away, then write the real code test-first with what you learned, or hide the unknown API behind a small interface you can test against.

Order of execution

From spike to tested code

Tap the steps in the order a developer works.

Test-first for bug fixes: reproduce with a failing test

A regression test is a test kept after a bug fix so the bug cannot come back silently. Name it after the bug, such as searchIgnoresCase.

Every bug report is a missing test. Write a test that reproduces the bug and fails for the reason the user saw, then fix the code.

Fixing a bug test-first. A bug report arrives. Write a test that reproduces it and watch it fail (red). Fix the code until that test passes and all other tests still pass (green). Keep the test as a regression test, so the bug cannot return unnoticed.

Example 3 · A bug fix, test first: search must ignore case

SearchBugFix.javaJava
import java.util.List;
public class SearchBugFix {    // Bug report: "Searching 'redmi' shows nothing, but 'Redmi' works."    static boolean matchesBuggy(String productName, String query) {        return productName.contains(query);    }
    static boolean matchesFixed(String productName, String query) {        return productName.toLowerCase().contains(query.trim().toLowerCase());    }
    interface Matcher {        boolean matches(String productName, String query);    }
    static void runTests(String label, Matcher m) {        System.out.println("-- " + label);        check("finds by exact word", true, m.matches("Redmi Note 13 5G", "Redmi"));        check("does not find other products", false, m.matches("Clean Code", "Redmi"));        check("BUG: lower-case query finds the product", true, m.matches("Redmi Note 13 5G", "redmi"));    }
    static void check(String name, boolean expected, boolean actual) {        System.out.println((expected == actual ? "PASS " : "FAIL ") + name);    }
    public static void main(String[] args) {        runTests("before the fix", SearchBugFix::matchesBuggy);        runTests("after the fix", SearchBugFix::matchesFixed);        System.out.println("found: " + List.of("Redmi Note 13 5G", "Clean Code", "boAt Airdopes 141").stream()                .filter(name -> matchesFixed(name, " REDMI ")).toList());    }}
Output
-- before the fix
PASS finds by exact word
PASS does not find other products
FAIL BUG: lower-case query finds the product
-- after the fix
PASS finds by exact word
PASS does not find other products
PASS BUG: lower-case query finds the product
found: [Redmi Note 13 5G]

What this code does

  • The new test fails against the old code for exactly the reason in the bug report. Only then is the code changed; the old tests still pass, so the fix broke nothing.
  • The bug test stays in the suite forever as a regression test. If someone later "simplifies" the search back to contains(query), it fails at once.

Example 4 · The bug's regression test in JUnit 5

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

Java
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;
class ProductNameMatcher {    static boolean matches(String productName, String query) {        return productName.toLowerCase().contains(query.trim().toLowerCase());    }}
class ProductNameMatcherTest {
    @Test    void findsByExactWord() {        assertThat(ProductNameMatcher.matches("Redmi Note 13 5G", "Redmi")).isTrue();    }
    // Regression test for the bug "searching 'redmi' shows nothing"    @ParameterizedTest(name = "query \"{0}\" finds Redmi Note 13 5G")    @ValueSource(strings = {"redmi", "REDMI", " Redmi ", "note 13"})    void searchIgnoresCaseAndSpaces(String query) {        assertThat(ProductNameMatcher.matches("Redmi Note 13 5G", query)).isTrue();    }}
Sample output
[INFO] Running com.shoplite.product.ProductNameMatcherTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in com.shoplite.product.ProductNameMatcherTest

What this code does

  • The comment and the test name say why the test exists, so nobody deletes it as "obvious". The table also covers close relatives of the bug: upper case, spaces and a phrase in the middle of the name.
  • In a commit, the regression test and the fix travel together: a reviewer can see the test was red before the change and green after it.

Run all the other tests too. This order proves three things: you understood the bug, your fix really fixes it, and the bug cannot return unnoticed.

Common mistake: fixing the code first and writing the test afterwards. You never saw the test fail, so you cannot be sure it catches the bug.

Common myths about TDD

Test coverage is the share of code lines that run while the tests run. It shows which lines were executed, not whether the results were checked.

Four myths come up again and again, in teams and in interviews:

  • "TDD means no design." The design moves into small steps: tests shape method names and dependencies, and the refactor step is pure design work. Big structural decisions (layers, database) still need thought up front.
  • "TDD means 100% coverage." Coverage is a side effect, not the goal. Code written test-first is usually well covered, but a line can be covered by a test that checks nothing.
  • "TDD makes delivery slower." Writing tests takes time today; it saves debugging, manual re-checking and regressions later. Teams usually see the payoff within a few releases.
  • "You must do TDD for everything." No: use it where the answer is known in advance, and use spikes or manual checks where it is not.

Next step

Check your understanding

10 quick questions