Test-Driven Development (TDD): A Practical Guide
December 5, 2026 · 10 min read

Test driven development (TDD), usually written test-driven development, is a way of writing software in which you write a small failing test first, then write just enough code to make it pass, then tidy the code while the tests keep you safe. You repeat that loop every few minutes. The result is code that is tested by design, built in small verified steps, and shaped by how it will actually be used.
TDD was popularised by Kent Beck in his 2002 book Test-Driven Development: By Example, and it has found a new audience with AI coding agents. Beck himself describes building a B+ tree library with AI help by enforcing TDD discipline and refusing shortcuts such as disabled tests. This practical guide explains the red-green-refactor cycle, walks through a complete TDD session in JavaScript with real test output, summarises what the research says, and shows how to use tests to keep both humans and AI agents honest.
What Is Test Driven Development?
In traditional development, you write the code and then, if time allows, write tests for it. TDD reverses the order. Each new behaviour starts as a test that describes what the code should do, written before the code exists. Because the test fails at first, you know it is genuinely checking something. Because you write only enough code to pass it, you avoid building features nobody asked for. And because every behaviour has a test, you can restructure the code later without fear.
TDD is as much a design technique as a testing technique. Writing the test first forces you to decide how the code will be called, what it returns and how it fails, before you think about how it works inside. Code that is hard to test is usually hard to use, and TDD makes that obvious immediately.
The Red-Green-Refactor Cycle
- Red: write one small test for the next behaviour you need. Run it and watch it fail, ideally with a clear message.
- Green: write the simplest code that makes the test pass. Resist adding anything the tests do not require yet.
- Refactor: with all tests passing, improve names, remove duplication and simplify. Run the tests after every change.
Each loop should take minutes, not hours. If a step feels too big, write a smaller test. Robert C. Martin's rewritten second edition of Clean Code lists TDD as a core discipline, alongside practices such as test && commit || revert and working in small batches.
A TDD Example in JavaScript
Suppose a project-management app needs to turn durations typed by users, such as "45s", "2m" or "1h 30m", into seconds. Using Node.js's built-in test runner, we start with the tests. In a real session you would add these one at a time, going round the loop for each; here they are together for brevity:
// duration.test.mjs: written first, one behaviour at a time
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseDuration } from "./duration.mjs";
test("parses seconds", () => assert.equal(parseDuration("45s"), 45));
test("parses minutes", () => assert.equal(parseDuration("2m"), 120));
test("combines hours and minutes", () => assert.equal(parseDuration("1h 30m"), 5400));
test("ignores spaces and capital letters", () => assert.equal(parseDuration(" 1H30M "), 5400));
test("rejects nonsense with a clear message", () => {
assert.throws(() => parseDuration("soon"), /Invalid duration: "soon"/);
});
Next, create the function so the tests can run, but do not implement it yet:
// duration.mjs, step 1 (red): the function exists, but does nothing yet
export function parseDuration(text) {
throw new Error("Not implemented");
}
Red: watch the tests fail
$ node --test
✖ parses seconds
✖ parses minutes
✖ combines hours and minutes
✖ ignores spaces and capital letters
✖ rejects nonsense with a clear message
ℹ pass 0
ℹ fail 5
Every test fails, including the last one: it expects an "Invalid duration" error but receives "Not implemented", which proves the test checks the message rather than just any error. A test you have never seen fail is a test you cannot fully trust.
Green, then refactor
Going one test at a time, the first passing version simply parsed seconds, the next added minutes, and so on. Once all five passed, the refactor step replaced a growing chain of if statements with a lookup table and a regular expression. This is the final version:
// duration.mjs, after green and refactor: small, readable, fully covered by the tests
const SECONDS_PER_UNIT = { h: 3600, m: 60, s: 1 };
export function parseDuration(text) {
const input = text.trim().toLowerCase().replace(/\s+/g, "");
const parts = [...input.matchAll(/(\d+)([hms])/g)];
const understood = parts.map(([part]) => part).join("");
if (parts.length === 0 || understood !== input) throw new Error(`Invalid duration: "${text}"`);
return parts.reduce((total, [, amount, unit]) => total + Number(amount) * SECONDS_PER_UNIT[unit], 0);
}
$ node --test
✔ parses seconds
✔ parses minutes
✔ combines hours and minutes
✔ ignores spaces and capital letters
✔ rejects nonsense with a clear message
ℹ pass 5
ℹ fail 0
All five tests pass. Because they were written first, they cover every behaviour the function promises, including the error message a user will see. If someone later adds support for days, the existing tests will immediately reveal anything they break.
What the Research Says
The best-known industrial study of TDD, published in 2008 by researchers from Microsoft, IBM and North Carolina State University, followed four teams that adopted it. It found that pre-release defect density fell by between 40% and 90% compared with similar projects that did not use TDD, while the teams estimated that initial development took 15% to 35% longer. Later reviews of the wider research describe the evidence as more mixed, with the benefits depending on the team, the experience level and how strictly TDD is practised.
A fair summary: TDD tends to reduce defects and improve design, it costs some extra time up front, and that time is often recovered through less debugging and safer changes. It is not magic, and doing it badly, with brittle tests tied to implementation details, can make code harder to change rather than easier.
Benefits of Test Driven Development
- Fewer defects: every behaviour is tested from the start, including edge cases you think about while writing tests.
- Better design: testable code tends to be modular, with clear inputs and outputs and fewer hidden dependencies.
- Living documentation: tests show exactly how the code is meant to be used, and unlike comments, they cannot silently go out of date.
- Safe refactoring: a comprehensive suite lets you improve code continuously, which keeps it clean over years.
- Focus and momentum: one small, clear goal at a time reduces overwhelm and makes progress visible.
- Faster debugging: when a test fails, the bug is in the few lines you just changed.
Common Objections and Misconceptions
- "TDD means 100% coverage." High coverage is a side effect, not the goal. The goal is confidence in behaviour.
- "TDD is too slow." It is slower to type, but usually faster to finish, because less time goes on debugging and rework.
- "You cannot TDD user interfaces." You can test UI logic and components first; visual details are better checked with other tools.
- "TDD only means unit tests." Many teams start a feature with a failing acceptance or integration test, then drive the details with unit tests. Our guide to unit vs integration testing explains the levels.
- "Our legacy code has no tests." Start when you fix a bug: write a failing test that reproduces it, then fix it. Coverage grows where change happens.
TDD with AI Coding Agents
AI coding agents and TDD fit together naturally. Tests give an agent an objective definition of "done", and a fast test suite lets it check its own work in a loop. They also protect you from the agent's worst habits. Beck's account stresses refusing shortcuts such as disabled tests, and agents under pressure to report success will sometimes weaken or skip a test rather than fix the code. Treat tests as a contract the agent may not change without your permission.
A practical workflow: write or approve the tests yourself, ideally from the acceptance examples in a short specification as described in our guide to spec-driven development. Then ask the agent to make them pass one at a time, run the full suite after each change, and refactor once everything is green. Put the rules in your agent instructions: never modify tests to make them pass, never skip tests, and stop and ask when a test seems wrong. Our guide to AI coding agents covers how to set those boundaries.
TDD in Other Languages
The cycle is identical in every language; only the tools change. Python developers use pytest, Java developers JUnit and C# developers xUnit or NUnit. Go has testing built into the toolchain with go test, as our Golang tutorial shows, and Rust's cargo test runs tests written right next to the code, covered in our guide to Rust for beginners. Built-in test runners remove all set-up friction, which makes these languages especially pleasant for practising TDD.
TDD, Continuous Integration and Small Commits
TDD produces a steady rhythm of small, tested changes, which is exactly what continuous integration needs. Each green test is a safe point to commit, and frequent commits to a shared main branch keep integration pain low, the core idea of trunk-based development described in our guide to Git branching strategies. Combined with the readability habits in our guide to clean code, the refactor step keeps the codebase healthy as it grows.
How to Start Practising TDD
- Start with code katas: small exercises such as FizzBuzz, a bowling score calculator or a string calculator, where the problem is easy and you can focus on the rhythm.
- Use TDD for bug fixes first: reproduce each bug with a failing test before fixing it.
- Pick pure logic next: pricing, validation, parsing and date calculations are perfect TDD territory.
- Keep the loop tight: if you have been red for more than ten minutes, undo and take a smaller step.
- Pair with someone experienced, or review your test-writing in pull requests, to build good habits early.
Frequently Asked Questions
What is test driven development?
Test driven development is a practice in which you write a failing test for a small piece of behaviour, write just enough code to pass it, then refactor, repeating the cycle in short steps.
What does red-green-refactor mean?
Red means writing a test that fails, green means writing the minimum code to make it pass, and refactor means improving the code's design while all tests stay green.
Does TDD really reduce bugs?
Industrial case studies at Microsoft and IBM found pre-release defect density fell by 40% to 90% with TDD, at the cost of 15% to 35% more initial development time. Results vary by team and practice.
Is TDD worth it for small projects?
Often yes for logic that matters, such as pricing, permissions or data processing. For throwaway prototypes, a lighter approach is usually fine, but add tests before the prototype becomes the product.
Can you use TDD with AI coding tools?
Yes, and it works well. Approve the tests yourself, let the AI make them pass in small steps, and never allow it to delete, skip or rewrite tests just to get a green result.
What is the difference between TDD and BDD?
Behaviour-driven development extends TDD by describing behaviour in business language, often as given, when and then scenarios, so developers, testers and stakeholders can agree on examples before coding starts.
Adopt Test Driven Development with Confidence
We help teams introduce test driven development, build reliable test suites and set up AI-assisted workflows that keep quality high as delivery speeds up. Get in touch to discuss training or a quality review.