Test-driven development (TDD) is a way of writing code in which you first write a small automated test for behavior that doesn't exist yet, watch it fail, write just enough code to make it pass, and then tidy the design while every test stays green. That loop is usually called red-green-refactor. One turn takes a few minutes, and you repeat it until everything you set out to build is covered by a test.
Kent Beck popularized the practice as part of Extreme Programming, and it works the same way in any language that has a test runner.
The cycle, step by step
Beck's current summary of the method, which he calls Canon TDD, starts with a step most explanations skip. Before you write any test, you write a list.
- Write a test list. Note the behaviors the change should have, the edge cases you can think of, and the existing behavior it must not break. Keep the list about behavior; how to implement it is decided later.
- Turn one item into a test. A real, runnable test with setup, a call and an assertion. This is where you design the interface: what the function is called, what it takes, what it returns.
- Make it pass. Change the code until this test and every earlier one pass. If you spot another case along the way, add it to the list instead of handling it now.
- Refactor if it helps. With everything green, improve the structure: names, duplication, where things live. Behavior doesn't change in this step, so the tests stay green throughout.
- Repeat from step 2 until the list is empty.
The red part matters more than it looks. Running a new test and seeing it fail, for the reason you expected, proves the test can detect the missing behavior. A test you have never seen fail may be passing for the wrong reason: the runner never collected it (pytest skips functions whose names don't start with test), it calls the wrong function, or its assertion can't fail.
A worked example: does this leave block this shift?
Katas like FizzBuzz hide the interesting part, so here is a simplified rule from staff rostering, the domain of Oplist, a hospital scheduling client we build for. Given a period of leave and a shift, does the leave stop that person from working the shift? The starting test list:
- a full-day leave on the shift's date blocks it
- a leave on another day doesn't
- a two-hour leave in the middle of the shift blocks it
- a leave that ends exactly when the shift starts doesn't
- a night shift that runs past midnight is blocked by a leave the next morning
Red. The first item as a pytest test, in test_rota.py:
from datetime import datetime as dt
from rota import Period, blocks
DAY_SHIFT = Period(dt(2026, 11, 2, 8), dt(2026, 11, 2, 16))
def test_full_day_leave_blocks_that_days_shift():
sick_day = Period(dt(2026, 11, 2), dt(2026, 11, 3))
assert blocks(sick_day, DAY_SHIFT)Running pytest fails at once because the rota module doesn't exist. That counts as red. Notice what writing the test first forced: before any implementation, we had to decide on a Period with a start and an end, and a blocks(leave, shift) function that answers yes or no.
Green. The least code that passes, in rota.py:
from dataclasses import dataclass
from datetime import datetime
@dataclass(frozen=True)
class Period:
start: datetime
end: datetime
def blocks(leave: Period, shift: Period) -> bool:
return Truereturn True looks like cheating, and it is meant to. It proves the test is wired up, and it leaves the next test to force real logic out of you. Beck's book calls this move "fake it".
Triangulate. That's Beck's name for adding examples until they force a general solution. The second item, a leave on the following day, fails against return True. One simple change that passes both tests is to check whether the leave covers the whole shift:
def blocks(leave: Period, shift: Period) -> bool:
return leave.start <= shift.start and shift.end <= leave.endGreen again. Then the third item goes red:
def test_two_hour_leave_inside_the_shift_blocks_it():
dentist = Period(dt(2026, 11, 2, 10), dt(2026, 11, 2, 12))
assert blocks(dentist, DAY_SHIFT)A two-hour dentist appointment sits inside the shift without covering it. "Covers" was the wrong rule, and a test caught it before any roster depended on it. The rule we want is "overlaps":
def blocks(leave: Period, shift: Period) -> bool:
return leave.start < shift.end and shift.start < leave.endThe last two items pass on their first run. The strict < already treats a leave that ends at 08:00 as compatible with a shift that starts at 08:00, and full datetimes handle the night shift with no special code. A test that passes immediately deserves a second look: break the code on purpose for a moment and check that the test fails. If it does, keep it, because it documents a case the next developer will wonder about.
Refactor. With five green tests the structure can change safely. Overlap is a property of two periods, so it moves onto Period:
@dataclass(frozen=True)
class Period:
start: datetime
end: datetime
def overlaps(self, other: "Period") -> bool:
return self.start < other.end and other.start < self.end
def blocks(leave: Period, shift: Period) -> bool:
return leave.overlaps(shift)No behavior came in with the refactor. If the rule has to change later, say to ignore leaves shorter than an hour, that change starts with a new failing test.
A real list keeps growing as you learn the domain. Oplist receives leave from hospitals' HR systems with its type attached: sick leave, hourly leave, block leave such as training. The rostering rules depend on the type, and some types take precedence over others, so a rostering tool can't treat every absence as plain "unavailable". In this example that would mean blocks() soon needs the leave type as an argument, and each precedence rule gets its own failing test before the code that applies it.
Mistakes that make TDD feel slow
When TDD feels slow, the cause is usually one of these:
- Refactoring while a test is red. Get to green with the crude version first. If you change structure and behavior at the same time and something breaks, you can't tell which change did it.
- Adding behavior during the refactor. A new case means a new test.
- Turning the whole list into tests up front. The design shifts as you go and you end up rewriting them; Beck lists this among the common mistakes in Canon TDD.
- Pasting the computed result into the assertion. If you run the code and copy what it printed into
assert result == ..., the test checks the code against itself. Work out the expected value independently. - Testing private details. Tests that assert on internal calls and intermediate state break on every refactor, exactly when you need them to stay green. Test through the public interface.
- Taking steps that are too big. If you have been red for a long stretch, revert and take a smaller step.
- Chasing a coverage number. Coverage shows which lines ran; it says nothing about whether the test checked the result.
Code that is painful to test usually has too many responsibilities or hides its dependencies. Writing the test first means you feel that pain before the code exists, so TDD tends to push code towards small units with explicit inputs. The SOLID principles push in the same direction from the design side.
Mocks and test doubles
TDD needs fast tests, which raises the question of what to do about databases, HTTP APIs, the clock and email. Martin Fowler's Mocks Aren't Stubs describes two styles. Classical TDD (often called the Chicago or Detroit school) uses real objects where it can and a test double only when the real thing is awkward. Mockist TDD (the London school) replaces any collaborator with interesting behavior by a mock and verifies the interactions.
A practical rule: use real objects inside your own code, and put doubles at the edges you don't control, such as third-party APIs, payment providers, the system clock and message queues. Heavily mocked tests are tied to how the code is written, so they fail when you restructure it, and the refactor step stops being cheap. Where you mock an external API, keep a few slower integration tests against the real service or its sandbox so the mock and reality don't drift apart.
What the research says
The best-known industrial study is still Nagappan et al. (2008). Three Microsoft teams and one IBM team that adopted TDD saw pre-release defect density fall by 40–90% compared with similar projects that didn't use it, and the teams reported that initial development took 15–35% longer. These were case studies, and the comparison projects differed in more than the practice.
Later studies are less clear-cut. Fucci and colleagues (2017) logged how 39 professionals actually worked across 82 development tasks and found that whether the test came before or after the code had no important effect on quality or productivity. What did matter was working in small, steady steps.
Our reading: the evidence backs the short cycle, and the habit of having a test for every change, more firmly than it backs the strict test-first order. Writing the test first is still the simplest way to keep steps small and to see every test fail once. Just don't sell TDD to your team with a defect-reduction percentage, and expect the first few weeks to be slower. That time comes back on code that keeps changing, because every later change runs against tests that already describe the behavior. On a prototype you delete next month, it never comes back.
Where TDD pays off, and where it doesn't
It earns its keep on:
- business rules with many edge cases, such as pricing, eligibility, scheduling, tax and payroll, where the test list doubles as a specification
- bug fixes: write a test that reproduces the bug, watch it fail, then fix it, and that bug can't quietly return
- parsers, validators, converters and anything else with clear inputs and outputs
- code you are about to refactor
It's a poor fit for:
- spikes and prototypes, when you don't yet know what you are building; explore without tests, throw the spike away, then build the real version test-first
- visual layout, which is better judged by eye, screenshots or visual regression tools
- thin glue over a framework, where the test would only restate the configuration
Code that calls an LLM
Features built on a language model have two halves. Whether the model pulls the right fields out of a document is a question of quality across many real inputs, so you check it with an evaluation set. The code around the model, which validates the output, retries and routes around failures, is ordinary deterministic code and suits TDD well.
In the field-ticket automation we built with an agency partner for an oilfield services company, what broke in production was mostly the LLM API's rate limits (HTTP 429), and the fix was falling back to alternative models. "On a 429, send the document to the next model" is easy to state as a test before you write it. The extraction itself was checked a different way: on real tickets, for a month, before going live.
Adding tests to legacy code
TDD assumes you can run the code inside a test. Legacy code often can't be: it opens a database connection in a constructor, calls the network, or reads the current date. The standard approach comes from Michael Feathers' book Working Effectively with Legacy Code:
- Write characterization tests. Run the existing code with representative inputs and assert on what it does today, bugs included. Their job is to tell you when behavior changes; whether today's behavior is right is a separate question.
- Find a seam: a place where you can swap a dependency with the smallest possible edit, for example by passing the clock or the repository in instead of creating it inside.
- Test-drive the code you add or change from then on.
Don't stop to cover the whole codebase first. Coverage grows where the changes happen, which is where it's worth the most. For the bigger decision of whether to keep changing an old system or replace it, see our post on legacy system modernization.
TDD with AI coding assistants
Coding agents have made test-first more useful. An agent stops when the work looks finished, and a failing test gives it a concrete target it can check by itself. Kent Beck described building a B+ tree library with an agent in Augmented Coding: Beyond the Vibes (June 2025). His instructions told it to follow red-green-refactor, take the next unmarked test from a plan file and write only enough code to pass it. He also watched for warning signs: features he hadn't asked for, and the agent "cheating" by disabling or deleting tests.
One way to divide the work:
- Write or approve the test list yourself. That's the part that needs domain knowledge.
- Have the agent write one test, run it and show you that it fails for the expected reason.
- Let it implement, then run the whole suite.
- Review changes to test files separately from the rest of the diff. A test that was weakened so the code could pass is exactly the failure you are looking for.
Bringing TDD to a team
- Pilot it on one module that has real rules and a queue of upcoming changes. A day-one mandate for the whole codebase mostly produces tests written afterwards to satisfy the rule.
- Pair or mob for the first sessions. The rhythm of small steps is easier to pick up by watching someone than from a slide.
- Run the tests on every push and block merges while they are red; a suite that only runs on laptops decays fast. Our GitHub Actions CI/CD post covers the setup.
- Keep unit tests fast enough, a few seconds for the module you are working on, that people run them after every change.
- Use synthetic fixtures, never copies of production personal data.
- After a couple of months, judge the pilot on what you care about: defects that reached users, how often a change broke something else, and whether people are less nervous touching that code.
Frequently asked questions
Is TDD the same as unit testing?
No. Unit testing is a kind of test; TDD is an order of work that happens to produce mostly unit tests. You can test-drive at other levels too, for example by starting a feature with a failing API-level test and working inwards (often called outside-in or double-loop TDD).
What is the difference between TDD and BDD?
BDD (behavior-driven development) grew out of TDD. Dan North described it in a 2006 article, written for people who were stuck on where to start and what to test. It describes behavior in business language, usually as Given/When/Then scenarios written in Gherkin and run with Cucumber, behave or pytest-bdd. Many teams use BDD scenarios for the acceptance criteria they agree with the product owner and TDD for the code underneath.
What tools do you need for TDD?
A test runner for your language, and nothing else: JUnit for Java and Kotlin, pytest for Python, Jest, Vitest or Node's built-in node:test for JavaScript and TypeScript, xUnit or NUnit for .NET, and the standard testing package in Go. Use the one your stack already has. It matters more that the tests for the module you are changing finish in seconds, so set up a watch mode or an editor shortcut that reruns them.
Can you use TDD for frontend code?
For behavior, yes. Render the component, act on it the way a user would (type into a field, click a button) and assert on what appears or which request goes out. Testing Library, a common choice for React, Vue and plain DOM tests, recommends finding elements by role and label, as a user or a screen reader would. Tests written that way don't depend on CSS classes, so restyling doesn't break them. Layout and visual polish are still better checked by eye or with screenshot tests.
If you have a codebase that has to keep changing without breaking what already works, write to us.
Related Articles
WMS vs TMS: What Each Does and Which One You Need First
A WMS runs what happens inside the warehouse; a TMS runs what happens after the truck leaves. Where they meet, which to buy first, and when you need neither.
Read More: WMS vs TMS: What Each Does and Which One You Need FirstSaaS Pricing Models: How to Choose One and Bill for It
The main SaaS pricing models, when each one fits, and the decision to make first: your value metric. Plus what your pricing asks of the billing code.
Read More: SaaS Pricing Models: How to Choose One and Bill for ItSaaS Metrics: What to Track, How to Calculate It, What Good Looks Like
The core SaaS metrics with formulas and worked examples, what recent benchmarks say is normal, and the definition mistakes that quietly distort MRR, NRR and LTV.
Read More: SaaS Metrics: What to Track, How to Calculate It, What Good Looks Like
