What Is Test-Driven Development (TDD)? A Guide with Examples

what is tdd

TDD stands for test-driven development: write a failing test, write just enough code to pass it, then refactor. This guide walks through the cycle with one feature built in Java and Python, plus the Detroit and London schools, AI assistants, and when to skip it.

Key takeaways
The 30-second version of this article
Test-driven development (TDD) means writing a failing automated test before the code it checks. Developers then write just enough code to pass the test and refactor while every test stays green, repeating this red, green, refactor loop for each small behavior until the feature is complete and covered by fast tests.
A worked TDD cycle starts with a test list. For a checkout discount, the tests cover no code, a valid SAVE10 code, and an unknown code. Each test fails first, gets the simplest passing code, and the design improves only during refactoring, the same way in Java with JUnit or Python with pytest.
TDD has two main schools. The Detroit, or classicist, style works inside-out with real objects and checks results. The London, or mockist, style works outside-in with mocks and checks interactions. Most teams mix both, then add integration tests so the layers are checked together as well as on their own.
With AI coding assistants, TDD matters more, not less. The developer writes the failing test that defines correct behavior, the assistant proposes code to pass it, and the developer runs and reviews the result. Letting one assistant write both tests and code tends to produce tests that mirror the bugs.

TDD stands for test-driven development. It is a way of writing software where you write a small automated test first, watch it fail, write just enough code to make it pass, and then clean the code up. You repeat that loop for every small piece of behavior until the feature is done.

It sounds backwards the first time you hear it. In practice it keeps changes small, gives you a safety net for refactoring, and leaves behind a suite of fast tests that describe what the code is supposed to do. This guide covers the cycle, a worked example in Java and Python, the two main schools of TDD, how it works with AI coding assistants, and when it is not worth the effort.

TDD in one minute

  • What it is: a development practice where a failing automated test, usually a unit test, is written before the production code that makes it pass.
  • The loop: red (write a failing test), green (write the simplest code that passes), refactor (improve the design while every test stays green).
  • Where it came from: Kent Beck developed it in the late 1990s as part of Extreme Programming, according to Martin Fowler.
  • What you get: small, focused changes, a fast regression suite, and code that is designed to be testable from the start.
  • What it costs: more time up front, and a learning curve until the rhythm feels natural.

What is test-driven development?

Test-driven development is a design and development practice, not a testing phase. The test comes first and describes one small behavior the code does not have yet. The code then grows to satisfy that test, and nothing more.

Because every piece of production code is written in response to a failing test, the tests and the code evolve together. The result is what Fowler calls self-testing code: a codebase where you can run one command and know within seconds whether you broke something.

TDD testing mostly works at the level of unit testing: small, fast tests around functions, classes, and modules. It does not replace integration tests, end-to-end tests, or exploratory testing. It gives those later layers a much more stable base to build on.

The TDD cycle: red, green, refactor

TDD runs on a short loop that most developers know as red, green, refactor. Some teams call it fail, pass, refactor. The names come from the color most test runners use for failing and passing results.

The Fail-Pass-Refactor cycle of TDD

Each turn of the loop should take minutes, not hours. If you find yourself writing code for half an hour before you can run a test again, the step is too big.

How to do TDD

Before the loop: write a test list

Before writing any code, list the behaviors you expect the feature to have, one line each. This is an easy step to skip, and Fowler calls out the test list as a vital first step. Pick the simplest item on the list to start, and add new items whenever they occur to you during the work.

1. Red: write a failing test

Write one test for one behavior from the list. Run it and watch it fail. The failure matters for two reasons. It proves the test can fail, so it is not passing by accident. And the failure message tells you exactly what is missing, whether that is a class that does not exist yet or a wrong return value.

2. Green: write just enough code to pass

Write the simplest code that makes the failing test pass. Hard-coding a return value is fine at this stage if that is all the current test asks for. The next test will force a more general solution. The goal is to get back to a passing suite quickly, not to write the final design in one go.

3. Refactor: clean up with the tests as a safety net

With every test green, improve the code. Remove duplication, rename things, extract methods, and simplify logic. Refactoring means changing the structure without changing the behavior, so the tests should stay green after every small change. Refactor the test code too. Then pick the next item from the test list and start again.

banner5.png

Test-driven development example: one feature in Java and Python

Here is a small feature built test by test in two languages, so you can see the same cycle with JUnit and with pytest. The Java tests use the JUnit Jupiter API, which is the same in JUnit 5 and JUnit 6.

The feature: a checkout calculates an order total in cents. With no discount code, the total is the subtotal. The code SAVE10 takes 10% off. An unknown code is rejected with an error.

The test list:

  1. No code: the total equals the subtotal.
  2. SAVE10: the total is 10% lower.
  3. Unknown code: the checkout raises an error.

Amounts are whole cents, so the example avoids floating-point rounding. Integer division rounds any fraction of a cent down; a real checkout would add a test that pins its rounding rule.

Java with JUnit

Cycle 1, red. Start with the simplest item. The test refers to a Checkout class that does not exist yet, so the build fails. A compile error counts as red.

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class CheckoutTest {

    private final Checkout checkout = new Checkout();

    @Test
    void totalWithoutCodeIsSubtotal() {
        assertEquals(4000, checkout.total(4000, null));
    }
}

Cycle 1, green. The simplest code that passes returns the subtotal unchanged.

class Checkout {

    long total(long subtotalCents, String code) {
        return subtotalCents;
    }
}

Cycle 2, red. Add the discount test. It fails because the method still returns 4000.

    @Test
    void save10TakesTenPercentOff() {
        assertEquals(3600, checkout.total(4000, "SAVE10"));
    }

Cycle 2, green. Add just enough logic for SAVE10.

    long total(long subtotalCents, String code) {
        if ("SAVE10".equals(code)) {
            return subtotalCents * 90 / 100;
        }
        return subtotalCents;
    }

Cycle 3, red. An unknown code should be rejected. Right now it is silently ignored, so this test fails.

import static org.junit.jupiter.api.Assertions.assertThrows; // add to the imports at the top

    @Test
    void unknownCodeIsRejected() {
        assertThrows(IllegalArgumentException.class,
            () -> checkout.total(4000, "BOGUS"));
    }

Cycle 3, green. Add a check after the SAVE10 branch: if the code is not null, throw IllegalArgumentException. All three tests pass.

Refactor. The hard-coded string and the 90 / 100 arithmetic will not scale to a second code. Move the discounts into a lookup table, run the tests, and confirm they are still green. Behavior is unchanged, and adding a new code is now a one-line change plus a new test.

import java.util.Map;

class Checkout {

    private static final Map<String, Integer> PERCENT_OFF = Map.of("SAVE10", 10);

    long total(long subtotalCents, String code) {
        if (code == null) {
            return subtotalCents;
        }
        Integer percent = PERCENT_OFF.get(code);
        if (percent == null) {
            throw new IllegalArgumentException("Unknown discount code: " + code);
        }
        return subtotalCents * (100 - percent) / 100;
    }
}

See the JUnit user guide for setup with Maven or Gradle. The code works the same on JUnit 5 and JUnit 6, which share the Jupiter API.

Python with pytest

The same test list in Python. Write the first test in test_checkout.py and run pytest. It fails at collection because the checkout module does not exist. That is your red.

# test_checkout.py
from checkout import total


def test_total_without_code_is_subtotal():
    assert total(4000) == 4000

Green is one line: create checkout.py with def total(subtotal_cents, code=None): return subtotal_cents. Then add import pytest to the top of test_checkout.py and add these two tests one at a time, watching each fail before you change the code.

# test_checkout.py (continued)


def test_save10_takes_ten_percent_off():
    assert total(4000, "SAVE10") == 3600


def test_unknown_code_is_rejected():
    with pytest.raises(ValueError):
        total(4000, "BOGUS")

After the green steps and the same refactor as the Java version, the module looks like this, and all three tests pass:

# checkout.py
PERCENT_OFF = {"SAVE10": 10}


def total(subtotal_cents, code=None):
    if code is None:
        return subtotal_cents
    if code not in PERCENT_OFF:
        raise ValueError(f"Unknown discount code: {code}")
    return subtotal_cents * (100 - PERCENT_OFF[code]) // 100

The pytest documentation covers fixtures and parametrized tests, which help once a test list grows past a handful of cases.

What the example shows

  • Each test was written before the code that satisfies it, and each one failed first.
  • The green steps were deliberately naive. The design improved during refactoring, not up front.
  • The finished tests read like a specification: no code, SAVE10, unknown code. A new developer can learn the rules from them.
  • Adding a second discount code now starts with a new failing test, not with a change to the code.

Benefits of test-driven development

  • Fast feedback. You learn within seconds whether a change works, while the code is still fresh in your head.
  • Testable design. Code written to satisfy a test tends to have small functions, clear inputs and outputs, and few hidden dependencies.
  • A safety net for refactoring. Because each behavior you built has a test, you can restructure code with far less guessing about what you broke.
  • Built-in regression tests. The unit tests stay in the suite and run on every change, which supports regression testing as the codebase grows.
  • Living documentation. Tests show how each unit is meant to be called and what it returns, and unlike comments, they fail when they go out of date.
  • Smaller, focused steps. Working one test at a time breaks a large feature into pieces you can finish, review, and commit independently.

Drawbacks and when to skip TDD

TDD is a tool, not a rule. It pays off most where logic is complex and the code will live for a long time. It pays off least where you are still discovering what to build.

Common drawbacks:

  • It takes longer up front, especially while a team is learning it.
  • Tests that are tied to implementation details break on every refactor and slow the team down.
  • Heavy use of mocks can produce tests that pass while the real system fails.
  • It does not catch misunderstood requirements. If you write the wrong test, you get well-tested wrong code.

When TDD is a strong fit: business rules, calculations, parsers, validation, state machines, algorithms, bug fixes (write a test that reproduces the bug first), and any shared library other teams depend on.

When to consider skipping it: throwaway prototypes and spikes, UI layout and visual styling, exploratory work where the interface is still unknown, and thin glue code that only wires libraries together. A common pattern is to spike without tests, throw the spike away, and then rebuild the real version with TDD.

Detroit vs London: the two schools of TDD

There are two well-known styles of TDD. Most teams mix them, but knowing the difference helps you choose where to start and how much to mock. Martin Fowler describes the split as classical vs mockist testing in Mocks Aren't Stubs.

Detroit (classicist, inside-out)

London (mockist, outside-in)

Starting point

Core domain logic, then build outward

The outer behavior a user sees, then work inward

Collaborators

Real objects wherever practical

Test doubles (mocks) for collaborators

What tests check

State: the result or the object's state after the call

Interactions: which collaborators were called, and how

Design emerges

During refactoring

While writing tests, as each test reveals a collaborator and its role

Main risk

Gaps between layers until integration

Tests coupled to implementation, brittle on refactor

Good fit

Algorithms, domain models, libraries

Layered applications, service boundaries

The checkout example above is Detroit style: it tests the result and uses no mocks. A London-style version might start from an order service test and mock a discount repository before the Checkout class exists. Either way, pair the unit tests with integration testing so the layers are checked together too.

TDD with AI coding assistants

AI coding assistants generate code quickly, which makes a clear definition of "correct" more valuable, not less. TDD gives you that definition before the assistant writes anything.

A workflow that works well:

  1. Write the test list and the first failing test yourself. This is where you decide what the code should do. It is also the part an assistant cannot know from your codebase alone.
  2. Ask the assistant for the smallest code that passes. Give it the failing test and the error message, not a vague feature description.
  3. Run the tests yourself. Do not accept "this should pass." Green in your own runner is the only signal that counts.
  4. Refactor with the assistant, one change at a time. Run the suite after each suggestion.
  5. Review any tests the assistant writes. Check that each one fails without the code and asserts real behavior, not just that a function returns something.

The main trap is letting one assistant write both the tests and the code in one pass. The tests then tend to mirror the implementation, including its bugs. Keeping the human in charge of the test, and the assistant in charge of satisfying it, keeps the tests honest. For a wider view of where AI fits in QA, see AI in software testing.

Is TDD still relevant in 2026?

Yes. The cost of writing code has dropped with AI assistants, but the cost of knowing whether code is correct has not. TDD answers that second question. A failing test is a precise, executable statement of intent that both a developer and an assistant can work against, and the resulting suite catches regressions in generated code the same way it catches them in handwritten code.

What has changed is where the effort goes. Less time goes into typing the green step, and more goes into choosing good tests and reviewing what the assistant produced.

How TDD relates to BDD and ATDD

TDD has two close relatives that also put the test or specification first. Behavior-driven development (BDD) describes feature behavior as plain-language scenarios that developers, testers, and the business write together. Acceptance test-driven development (ATDD) starts from the acceptance criteria of a user story. TDD stays at the unit level, in code, written by developers.

Is Gherkin BDD or TDD? Gherkin is a BDD language. It describes behavior in Given, When, Then steps that non-developers can read, and tools such as Cucumber turn those steps into automated tests (see the Gherkin reference). Teams often use both: Gherkin scenarios define the feature from the outside, and TDD drives the code underneath. For a full comparison, read TDD vs BDD, and for the BDD side in depth, see BDD testing.

TDD vs traditional testing

Test-driven development

Traditional (test-after) testing

When tests are written

Before the code

After the code

Role of the test

Drives the design

Verifies the finished code

Feedback

Seconds, on every small change

Later, often after a larger batch of work

Coverage

Each behavior you listed has a test, because code is only written to pass one

Depends on discipline and time left at the end

Refactoring

Part of every cycle

A separate, often postponed task

Up-front effort

Higher

Lower, but defects surface later, when the code is less fresh

How TDD fits into Agile development

TDD and Agile share the same idea: work in small increments and get feedback fast. TDD applies that idea inside a single developer's loop, the same way Agile applies it to a sprint.

In practice, TDD fits Agile teams in a few ways:

  • Stories become test lists. Acceptance criteria on a user story translate naturally into the first tests to write.
  • Continuous integration stays green. Every commit arrives with tests, so the CI build is a reliable signal for the whole team.
  • Changing requirements are cheaper. When a requirement changes, you change a test first and let the failures show you exactly what code needs to move.
  • Pairing and mobbing. TDD gives a pair a shared rhythm: one person writes the failing test, the other makes it pass.

TDD testing frameworks by language

Any unit testing framework can support TDD. These are the common defaults:

Language

Framework

Notes

Java

JUnit 5 or JUnit 6

The standard for Java; JUnit 6 keeps the JUnit 5 (Jupiter) API and needs Java 17 or later

Python

pytest

Plain assert statements, fixtures, and parametrized tests

JavaScript and TypeScript

Jest or Vitest

Watch mode reruns tests on save, which suits the TDD loop

C# and .NET

xUnit.net or NUnit

Both integrate with Visual Studio and the dotnet CLI

Ruby

RSpec or Minitest

RSpec reads like a specification; Minitest ships with Ruby

Go

testing package

Built into the standard library, run with go test

Pick the framework your team already uses. A fast test runner with watch mode matters more for TDD than any specific feature.

TDD best practices

What to do:

  1. Keep each test to one behavior. One reason to fail makes failures easy to read.
  2. Name tests after the behavior, such as unknownCodeIsRejected, not after the method under test.
  3. Follow arrange, act, assert. Set up the data, call the code, check the result, in that order.
  4. Keep unit tests fast. If the suite takes minutes, people stop running it on every change.
  5. Make tests independent. Each test sets up its own data and can run alone or in any order.
  6. Treat test code like production code. Refactor it, review it, and keep it readable.
  7. Start every bug fix with a failing test that reproduces the bug.

Mistakes to avoid:

  1. Skipping the refactor step. Martin Fowler calls this the most common way he hears of TDD going wrong, and it leaves you with tested but messy code.
  2. Writing several tests before any code. Work one failing test at a time.
  3. Testing private methods and implementation details. Test behavior through the public interface so refactoring does not break tests.
  4. Mocking everything. Use real objects where they are fast and deterministic.
  5. Never watching a test fail. A test that has never been red may not test anything.
Try Katalon for free

Where TDD stops

TDD gives you confidence that each unit does what it should. It does not tell you whether the pages, APIs, and workflows a user touches work together in a real browser or device. That is the job of integration, end-to-end, and regression suites built on top of the unit tests.

Teams that practice TDD often automate those higher layers with a tool such as Katalon Studio, which covers web, API, and mobile tests. The principle is the same at every level: decide what correct looks like, write it down as a test, and let the test tell you when the code is done.

Frequently asked questions

Henrik (Minh Huy) Dao

Minh Huy Dao (Henrik) is a Senior Quality Engineer at Katalon, where he has worked since 2023. He has nearly 10 years of experience in QA and test automation, including roles at TMA Solutions, Axon Active and Doctor Anywhere. His work spans automation with Java, JavaScript and WebdriverIO, as well as CI/CD with Jenkins and leading Scrum teams.

Connect on LinkedIn →
True Platform has arrived

Test everything. Ship with confidence.

From generating test cases to spotting failures, Katalon's AI works across your entire pipeline, automatically.

The Next Evolution of Manual Testing: Introducing Katalon AI Test Runner

Introducing Katalon AI Test Runner. Watch it run manual test cases live, with evidence for every pass and fail.

Live webinar
9:00 to 10:00 AM EST · Live online
Alex MartinsVP of Strategy
Gia EspositoSenior Solutions Engineer
Save your seat