Key takeaway
- Test-driven development (TDD) explained: red-green-refactor, TDD vs BDD vs ATDD, a worked example, AI coding agents and what the research shows.
Test-driven development (TDD) is a way of building software in which a developer writes a small automated test that fails, writes just enough code to make it pass, and then refactors while every test stays green. Kent Beck developed the practice in the late 1990s as part of Extreme Programming, and Martin Fowler sums up the loop as red, green, refactor.
For engineering leaders in 2027, TDD matters for a new reason. AI coding assistants and agents now produce code faster than people can review it, and a failing test is one of the clearest ways to tell an agent what "done" means. Industrial studies report lower defect density in exchange for more initial development time, so the real decision is where that trade is worth making.
What is test-driven development (TDD)?
Martin Fowler defines TDD as "a technique for building software that guides software development by writing tests". It sits on top of unit testing, but the point is design and feedback rather than test coverage alone: thinking about the test first forces the developer to think about the interface first.
In December 2023 Kent Beck published Canon TDD to restate the workflow he intended. It has five steps:
Test list: write down the behaviours the change must cover, including existing behaviour that must not break. Leave implementation design out of this step.
Write one test: one automated test with setup, invocation and assertions. Interface decisions start here.
Make it pass: change the system until this test and all previous tests pass. Add new scenarios to the list as they appear.
Optionally refactor: make implementation design decisions once the test is green.
Repeat from step 2 until the test list is empty.
What happens in each phase of red, green, refactor?
| Phase | What the developer does | Mistake Beck warns about |
|---|---|---|
| Test list | Lists behaviours and edge cases before coding | Turning every item on the list into concrete tests at once, then making them pass one by one |
| Red | Writes one failing test for the next small behaviour | Copying computed values from the code into the expected values of the test |
| Green | Writes the simplest code that makes all tests pass | Deleting assertions so the test pretends to pass |
| Refactor | Improves structure while tests stay green | Mixing refactoring into making the test pass, or abstracting too soon |
Fowler notes that the most common way to get TDD wrong is to skip the third step. Without refactoring, the test suite grows but the design does not improve.
Fig 1: Workflow of test-driven development
How does a test-driven development example work in practice?
Take a pricing rule: orders of 100 or more get a 10 per cent discount, and negative totals are rejected. The test list has three items: no discount below the threshold, a discount at the threshold, and an error for negative totals. Each item becomes one red, green, refactor cycle using pytest.
Red. The first test fails because the function does not exist yet:
# test_pricing.py
from pricing import apply_discount
def test_no_discount_below_threshold():
assert apply_discount(order_total=99.0) == 99.0
Green. The simplest passing code is return order_total. The second test (100.0 should return 90.0) fails and forces the threshold logic; the third test forces the validation. After three cycles the tests and code look like this:
# test_pricing.py
import pytest
from pricing import apply_discount
def test_no_discount_below_threshold():
assert apply_discount(order_total=99.0) == 99.0
def test_ten_percent_discount_at_threshold():
assert apply_discount(order_total=100.0) == 90.0
def test_rejects_negative_totals():
with pytest.raises(ValueError):
apply_discount(order_total=-1.0)
# pricing.py
DISCOUNT_THRESHOLD = 100.0
DISCOUNT_RATE = 0.10
def apply_discount(order_total: float) -> float:
if order_total < 0:
raise ValueError("order_total must not be negative")
if order_total >= DISCOUNT_THRESHOLD:
return round(order_total * (1 - DISCOUNT_RATE), 2)
return order_total
Refactor. Pulling the magic numbers into named constants is a refactoring step: behaviour does not change, and all three tests stay green. For language-specific walkthroughs, see our guides to TDD in Python, TDD in Java with JUnit and unit testing in Go.
What is the difference between TDD, BDD and ATDD?
All three write tests before the code, but they differ in who writes the tests and at what level. Dan North introduced behaviour-driven development (BDD) because developers new to TDD kept asking where to start, what to test and how to name tests; his Introducing BDD article first appeared in Better Software magazine in March 2006. The Agile Alliance describes acceptance test-driven development (ATDD) as customer, development and testing perspectives working together to write acceptance tests before the functionality is built.
| Practice | Who writes the tests | Focus and format | When it fits |
|---|---|---|---|
| TDD | Developers | Small units of behaviour, written in an xUnit-style framework such as JUnit or pytest | Business logic, libraries, services and APIs where design feedback matters |
| BDD | Developers, testers and analysts together | Behaviour described as scenarios in the Given, When, Then form, often against user stories ("As a [X], I want [Y], so that [Z]") | Features where business rules need a shared, readable specification |
| ATDD | The "three amigos": customer, development and testing | Acceptance tests that act as requirements, written before implementation and sometimes automated | Work where agreeing what "done" means is the main risk |
The Agile Alliance records that Kent Beck mentioned ATDD in his 2003 book Test Driven Development: By Example but dismissed it as impractical, and that it became accepted practice in 2003 to 2004 as Fit and FitNesse spread. It also warns that tools can get in the way of ATDD's main purpose, which is conversation. In practice, many teams use ATDD or BDD for the outer acceptance loop and TDD for the inner code loop. To automate sprint planning and Scrum ceremonies around that loop, AgentScrum uses agentic AI to track blockers and monitor burndown.
How does TDD work with AI coding assistants and agents going into 2027?
The main change since this guide was first written is that a large share of code is now drafted by AI assistants and agents. Vendor guidance and practitioners now treat a failing test as the specification an agent works towards, and human review of the tests as the control point. For the wider picture, see our posts on agentic AI in software development and agentic AI for software testing. For automated quality assurance of AI systems themselves, see AgentQA.
Kent Beck on "augmented coding" (June 2025): in Augmented Coding: Beyond the Vibes, Beck describes instructing an agent to follow red, green, refactor and to keep structural and behavioural changes separate. He took back control of the design after early attempts stalled, and watched for three warning signs: loops, functionality he had not asked for, and cheating such as disabling or deleting tests.
GitHub Copilot: the GitHub blog's TDD with GitHub Copilot guide (May 2025) asks Copilot to create the test functions first, which is the red stage, then to create the implementation, and tells developers to review the plan and suggestions before accepting them.
Visual Studio Code: Microsoft's test-driven development guide sets up separate TDD Red, TDD Green and TDD Refactor custom agents linked by handoffs, which do not submit automatically, so a person reviews each phase. Its testing guide says not to accept deleted assertions, skipped tests or changed expected values just to get a passing result, and reminds teams that coverage shows which code ran, not whether the assertions are correct.
Claude Code: Anthropic's Claude Code best practices recommend prompts such as "write a failing test that reproduces it, then fix it", list "a failing test it has to turn green" as one way to tell the agent what done looks like, and advise enforcing checks that cannot have exceptions with hooks rather than with instructions alone.
Research points the same way. In Test-Driven Development for Code Generation, Mathews and Nagappan (manuscript prepared for ASE 2024) report that giving GPT-4 Turbo and Llama 3 70B the tests during generation improved correctness by 9.15 to 29.57 per cent on the MBPP and HumanEval benchmarks. These are benchmark puzzles, not enterprise codebases, so treat the result as direction rather than a forecast. To test and benchmark AI agents on your own workloads rather than public puzzles, see AgentEvaluation.
| Control for agent-written code | What it prevents | Where it comes from |
|---|---|---|
| A human writes or approves the failing test before the agent writes code | The agent defining "done" for itself | Beck, GitHub, VS Code guidance |
| Review step between red, green and refactor | Large unreviewed changes and unrequested features | VS Code handoffs; Beck's warning signs |
| Block edits that delete assertions, skip tests or change expected values | "Passing" by weakening the tests | VS Code testing guide; Beck |
| Enforce test runs with hooks and CI, not only prompts | Agents finishing without running the suite | Claude Code best practices |
What does peer-reviewed research say about TDD outcomes?
The evidence supports TDD, but with a cost and with caveats about why it works.
Industrial case studies: Nagappan, Maximilien, Bhat and Williams (Empirical Software Engineering, vol. 13, 2008) studied four industrial teams at Microsoft and IBM. Pre-release defect density fell by between 40 and 90 per cent compared with similar projects that did not use TDD, while the teams' subjective estimate was a 15 to 35 per cent increase in initial development time.
What actually drives the benefit: Fucci, Erdogmus, Turhan, Oivo and Juristo (IEEE Transactions on Software Engineering, DOI 10.1109/TSE.2016.2616877) analysed 82 data points from 39 professionals. Quality and productivity improvements were associated mainly with granularity and uniformity, meaning small, steady steps. Whether the test was written before or after the code had no important influence.
The practical reading for leaders: the short, disciplined cycle is what pays off, and teams should expect to spend more time up front. Measure your own defect escape rate and cycle time rather than promising a published percentage.
Which test frameworks support TDD going into 2027?
Most mainstream languages have a mature xUnit-style framework. Status below was checked against each project's own site on 11 November 2026.
| Framework | Language | Current status | When it fits |
|---|---|---|---|
| JUnit | Java, Kotlin | JUnit 6 is the current generation (6.0.0 released 30 September 2025; 6.1.3 released 7 August 2026); requires Java 17 and Kotlin 2.1 or above | JVM services and libraries |
| Mockito | Java | 5.x line; a mocking framework for Java unit tests | Isolating units from databases, APIs and other collaborators |
| pytest | Python | Documentation shows the 9.x line; requires Python 3.10+ or PyPy 3; uses plain assert statements | Python services, data and ML code |
| Jest | JavaScript, TypeScript | Latest stable version 30.5 | Node.js and front-end projects already on Jest |
| Vitest | JavaScript, TypeScript | v5.1.0; Vite-native and Jest-compatible | Projects built with Vite, or teams wanting a fast Jest-compatible runner |
| ScalaTest | Scala | 3.2.20; styles include AnyFlatSpec (replacing the older FlatSpec import used in earlier examples) | Scala services and data pipelines |
Whatever the framework, keep production and test code in separate source trees (for example src/main/java and src/test/java in Java) and name tests after the behaviour they check, so the suite reads as documentation and supports regression testing on every change.
What governance, security and cost questions should leaders ask?
| Area | Question to ask | What good looks like |
|---|---|---|
| Cost | Have we budgeted for slower initial delivery? | Plans allow for extra up-front time (15 to 35 per cent in the Nagappan study) and track defects found after release |
| Ownership | Who approves tests written by or for AI agents? | Tests are reviewed like production code, and a named engineer owns each suite |
| Integrity | Can an agent or developer weaken a test to get green? | Hooks, branch protection or review rules flag deleted assertions, skipped tests and changed expected values |
| Security | Are security rules expressed as tests? | Input validation, authorisation and error handling have explicit test cases that run in CI |
| Signal quality | Are we reporting coverage as if it were correctness? | Coverage is one input; defect escape rate and change failure rate are tracked alongside it |
How should an enterprise adopt TDD?
Pick a pilot: one service with frequent changes and clear business rules, where defects are expensive.
Teach the canon: start every change with a test list, one test at a time, and a separate refactor step.
Agree conventions: framework, folder layout, naming and how mocks are used.
Make tests the definition of done for agents: a person writes or approves the failing test before an assistant writes the code.
Enforce in the pipeline: run the suite on every commit and protect test files from silent weakening.
Measure locally: compare defect escape rate and cycle time before and after the pilot.
Extend outwards: add ATDD or BDD with product owners once the inner loop is routine.
When is TDD not the right fit?
Throwaway spikes and prototypes, where the goal is learning and the code will be discarded.
Visual layout and user experience work, which unit tests describe poorly; acceptance and exploratory testing fit better.
Performance and load behaviour, which needs dedicated performance testing rather than unit tests.
Legacy code without seams, where teams often need tests around existing behaviour before test-first work is practical.
Teams that already work in small, steady steps with test-last discipline: the Fucci study suggests granularity matters more than strict test-first order, so forcing a switch may add little.
What has changed since this guide was first written?
Kent Beck's Canon TDD (December 2023) added the explicit test list step and named common mistakes.
JUnit moved to version 6 with a Java 17 baseline, and ScalaTest examples now use AnyFlatSpec.
AI assistants and agents turned TDD into a control for machine-written code, with vendors publishing TDD workflows for Copilot, VS Code agents and Claude Code.
Performance tools such as JMeter were removed from this list, because load testing sits outside the TDD loop.
To map one release decision your coding agents should make, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop.
What should you plan for in 2027?
For teams carrying TDD into 2027, the practical steps are the ones already covered above, applied with more discipline as AI assistants write more code.
- Make tests the definition of done. A person writes or approves the failing test before an assistant writes the code.
- Protect the tests. Use hooks, branch protection or review rules to flag deleted assertions, skipped tests and changed expected values.
- Measure locally. Budget for slower initial delivery, then compare your own defect escape rate and cycle time before and after a pilot.
Frequently asked questions about test-driven development
What is TDD in software engineering?
TDD is a development technique in which you write a failing automated test for the next small behaviour, write just enough code to pass it, then refactor. Kent Beck developed it in the late 1990s as part of Extreme Programming.
What are the steps of red, green, refactor?
Red: write one failing test. Green: write the simplest code that makes all tests pass. Refactor: improve the design while the tests stay green. Beck's Canon TDD adds a test list before the first cycle.
What is the difference between TDD and BDD?
TDD is a developer practice at unit level. BDD, introduced by Dan North in 2006, describes behaviour in business language using Given, When, Then scenarios so that developers, testers and analysts share one specification.
Does TDD reduce defects?
In a 2008 study of four industrial teams at Microsoft and IBM, pre-release defect density fell by 40 to 90 per cent compared with similar non-TDD projects, with an estimated 15 to 35 per cent increase in initial development time.
Should AI coding agents follow TDD?
Guidance from Kent Beck, GitHub, Microsoft and Anthropic all treats a failing test as the clearest specification for an agent. The key controls are human review of tests and blocking any change that deletes assertions, skips tests or alters expected values to get a pass.
What should teams change about TDD in 2027?
Make a person-written or person-approved failing test the definition of done for any change an AI assistant writes, protect test files so assertions cannot be deleted or weakened silently, and compare your own defect escape rate and cycle time before and after a pilot.
Next Steps to Master Test-Driven Development and Testing
Consult with our experts on implementing Test-Driven Development (TDD) and TDD testing. Discover how various industries and departments leverage Agentic Workflows and Decision Intelligence to become more decision-centric. Utilize AI to automate and optimize unit testing, test automation, and software development processes, enhancing efficiency and responsiveness.
Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.
Ready to put AI agents to work? Explore ElixirClaw, the agentic OS platform to build, orchestrate and govern AI agents.
Explore the XenonStack platform family: ElixirData · ElixirClaw · ElixirHub · NexaStack · MetaSecure · Neural AI · AgentGRC · AgentSRE · AgentAnalyst · AgentInstruct · AgentRAI · AgentScrum · AgentSearch · AgentForce · AI Aviator · SAIF Aviator · CohortIQ · XenonStack AI · XenonStack UAE