Test-Driven Development (TDD): The Unit Under Test, Red-Green-Refactor and a Practical Guide
In TDD, the unit under test is the code a test exercises; what it depends on can be replaced. What that means, red-green-refactor and a worked example.

In test-driven development (TDD), the unit under test is the piece of code a test exercises and checks: a function, a method, a class or a small group of classes, chosen by the team. Everything the unit relies on but the test is not checking, such as a database, an API client or an ERP, is a depended-on component that you either keep real or replace with a test double.
TDD itself is a short loop: write a failing test for the next small behavior, write the code that makes it pass, then refactor. Deciding what the unit under test is, before you write the test, is what keeps that loop fast and the tests useful.
Where engini fits: TDD on your own logic needs no engini. engini comes in at the boundary, when the code under test calls an ERP, a CRM, a database or a system behind the firewall, or when an AI agent does. engini gives that code managed tools it can run deterministically from the Python or TypeScript SDK, the REST API or the CLI, with separate development, staging and production environments and toolsets that can keep a test read only. See the engini developer docs.
Key Takeaways
- The unit under test, also called the system under test (SUT), is whatever a given test exercises. It is defined from the test's point of view, not by a fixed size.
- Anything the unit depends on but the test does not verify is a depended-on component (DOC). You replace it with a test double when it is slow, unpredictable or has side effects.
- TDD is red, green, refactor: a failing test, the simplest code that passes, then a cleanup with the tests still passing.
- Kent Beck's "Canon TDD" starts one step earlier: write a list of test scenarios, then turn exactly one into a test at a time.
- When AI writes the code, tests become the specification. Never let a coding agent delete or change assertions to make a test pass.
- Code that writes to an ERP or bank system needs both: unit tests with the ERP replaced, and integration tests against a sandbox.
What is the unit under test in TDD?
The unit under test is the code a single test is written to verify. xUnit Patterns, Gerard Meszaros's reference for unit testing terms, defines the system under test (SUT) as "whatever thing we are testing" and says it "is always defined from the perspective of the test."
"Unit under test" is the everyday name for the SUT in a unit test. xUnit Patterns lists other names, depending on what is being tested:
Meszaros adds that parts of the application the test is not verifying "may still be involved as a depended-on component (DOC)." That distinction is the heart of the question: the unit under test is what your assertions check, and the DOCs are what it calls along the way.
How big is a unit?
A unit is as big as your team decides. Martin Fowler notes in UnitTest that object-oriented design "tends to treat a class as the unit," but that "the team decides what makes sense to be a unit for the purposes of their understanding of the system and its testing."
Fowler also describes two styles:
- Solitary unit tests replace every collaborator with a test double, so only the unit's own code runs.
- Sociable unit tests let the unit use its real collaborators, and assume they work.
In his words, "mockists insist upon solitary unit tests, while classicists prefer sociable tests." Most teams mix the two: real collaborators when they are fast and in-process, doubles for anything that crosses a network or writes data.
What is test-driven development?
Test-driven development is a way of writing software in which a failing automated test comes before the code that makes it pass. Fowler defines TDD as "a technique for building software that guides software development by writing tests," in three steps:
- Write a test for the next bit of functionality you want to add.
- Write the functional code until the test passes.
- Refactor both new and old code to make it well structured.
Red, green, refactor
The three steps are usually called red, green, refactor, after the colors of a test runner.
Fowler warns that skipping the refactor step is the most common way to undermine TDD; without it, the code becomes a pile of fragments that each pass a test.
Canon TDD: start from a test list
Kent Beck, who popularized TDD, restated the process in Canon TDD (December 11, 2023) with an explicit first step:
- Write a list of the test scenarios you want to cover.
- Turn exactly one item on the list into a concrete, runnable test.
- Change the code to make that test and all previous tests pass, adding items to the list as you discover them.
- Optionally refactor to improve the design.
- Repeat from step 2 until the list is empty.
The list is where you decide the unit under test and its cases before writing any code.
Test doubles: what replaces a depended-on component
A test double stands in for a depended-on component so the unit under test can run alone, fast and the same way every time. Fowler's TestDouble defines it as "a generic term for any case where you replace a production object for testing purposes," and names five kinds:
In Python, the standard library's unittest.mock exists for exactly this: it lets you "replace parts of your system under test with mock objects and make assertions about how they have been used." Its create_autospec builds a mock that enforces the real object's call signatures, so a test fails if your code calls a method that does not exist.
A worked example: TDD on payment matching code
Here is TDD on a small piece of finance code, with the unit under test and its depended-on component named up front. The example is illustrative.
The behavior: when a customer payment arrives, apply it to an open invoice in the ERP only if the match is certain; otherwise send it to an exception queue for the accounts receivable team.
The unit under test: a function apply_payment(payment, open_invoices, erp, queue) that decides and acts.
The depended-on components: erp, the client that posts a payment in the ERP, and queue, where exceptions go. Both are replaced with mocks, because the test checks the decision, not the ERP.
The test list:
- The payment amount equals one open invoice's balance, in the same currency: post the payment to that invoice.
- The currency differs: queue it with the reason "currency", post nothing.
- No open invoice has a balance equal to the payment: queue it with the reason "no exact match".
- Two open invoices have the same balance: queue it with the reason "ambiguous", rather than guess.
Red. Write test 1: one open invoice for 1,250.00 USD, a payment of 1,250.00 USD, and an assertion that erp.post_payment was called once with that invoice's ID and queue.add was not called. Run it. It fails because apply_payment does not exist.
Green. Write the simplest apply_payment that finds the invoice with an equal balance and calls erp.post_payment. Test 1 passes.
Repeat. Test 2 fails, because the function ignores currency; add the currency check. Test 3 fails until there is an exception path. Test 4 is the one that matters most: the first version would happily post to the first of two equal invoices, so the test forces the function to count matches and queue when there is more than one.
Refactor. Move the matching into a pure function, find_match(payment, open_invoices), that returns either one invoice or a reason. Now find_match can be tested without any mocks at all, and apply_payment only wires the decision to the ERP and the queue. All four tests still pass.
The ERP itself is not tested here. That is the job of an integration test against a sandbox, which our integration testing guide covers step by step. For the business problem behind the example, see our guide to unapplied cash and remittance matching.
TDD vs. BDD vs. ATDD
TDD, behavior-driven development (BDD) and acceptance test-driven development (ATDD) all write tests first; they differ in who reads the tests and how big the unit under test is.
In Gherkin, Cucumber's reference says Given steps "describe the initial context of the system," When steps "describe an event, or an action," and Then steps "describe an expected outcome, or result." Teams often use BDD or ATDD for the outside of a feature and TDD for the code inside it.
Common TDD mistakes
Most TDD problems come from tests that stop checking anything. Beck's Canon TDD lists the mistakes he sees most:
- Refactoring while making a test pass. Get to green first, then clean up. In Beck's words, "Make it run, then make it right."
- Deleting or weakening assertions so a failing test passes.
- Copying the computed value into the expected value, which turns the test into a copy of the code instead of an independent check.
- Writing tests with no assertions to raise coverage.
- Turning the whole test list into tests at once before making any of them pass.
- Abstracting too early. Beck: "Duplication is a hint, not a command."
Two more come from choosing the wrong unit under test:
- Units too small: tests that mock every line's collaborators break on every refactor, even when behavior does not change.
- Units too large: tests that run through the database, the network and the ERP are slow and fail for reasons unrelated to the code you changed.
TDD when an AI coding agent writes the code
TDD matters more when an AI agent writes the code, because the tests become the specification the agent works to. A coding agent that is told "make the tests pass" will do exactly that, and the fastest way to make a test pass is to change the test.
Practical rules for TDD with a coding agent:
- Write or review the test list yourself. The list is the specification; the agent can draft tests from it.
- Keep the red step. Have the agent run each new test and show it failing before it writes code.
- Protect the assertions. Tell the agent never to edit, delete or loosen an existing assertion, and review every diff to test files. Beck lists deleting assertions as a classic TDD mistake; with an agent, it can happen silently.
- Use real signatures for doubles. Autospecced mocks catch an agent calling a method that does not exist.
- Keep model output out of unit tests. If the code calls a language model, the model's answer varies between runs. Unit-test the deterministic code around it with a stub, and evaluate the model's behavior separately. Our guide to AI hallucination examples shows why that separation matters.
Testing code that writes to an ERP or other system of record
Code that writes to an ERP, a CRM or a bank's core system needs two layers of tests, and TDD covers only the first.
- Unit tests (TDD): the unit under test is your decision logic. The ERP client is a depended-on component, replaced with a mock or stub, so tests run in milliseconds and never touch real data.
- Integration tests: the unit under test is the boundary itself. Run the real call against a sandbox, with exact inputs, and check what landed in the system. Plan for sandbox refreshes, which can reset credentials; see our note on NetSuite sandbox refreshes.
The design rule that makes both easy is the one from the worked example: keep the decision in a pure function and the side effect in a thin layer around it.
How engini fits into test-driven development
engini sits at the boundary in the second layer: the calls your code, or an AI agent, makes into systems of record. It does not replace your test framework or your unit tests.
- Deterministic tool runs. From the Python or TypeScript SDK, the REST API or the CLI, your code can run one action with exact inputs and no model choosing it, which is the shape of an integration test. The SDK also works as a plain typed API client (scripted automation), so the ERP client in your code is a thin, mockable layer.
- Separate environments. A workspace has development, staging and production environments, and an API key is tied to one workspace and one environment. Point development at sandbox connections and production at production.
- Tests in CI. The CLI authenticates from an environment variable, returns documented exit codes and outputs JSON when piped, so a pipeline can branch on the result (run engini in CI/CD).
- Read-only test runs. A toolset limits an agent or a script to the tools and the connection you choose, for example read only, enforced on the server for SDK, API and CLI calls.
- Your real setup. Custom fields and custom objects are read live from each system's own configuration, so integration tests run against the fields your account actually has.
- A record of every run. Every run is recorded under the user who triggered it, so you can see exactly what a test wrote.
When you do not need engini: TDD on your own business logic, services you own, or a test suite that never touches an external system. engini matters when the code under test has to act in an ERP, CRM, core banking or legacy system, including systems behind your firewall, or when an AI agent is the caller. For coding agents, point them at docs.engini.ai/llms.txt.
Frequently Asked Questions
What is the unit under test in TDD?
The unit under test is the code a single test exercises and verifies, such as a function, method or class. Everything else it calls is a depended-on component that you may replace with a test double.
What is the difference between the unit under test and the system under test?
They mean the same thing in a unit test. "System under test" (SUT) is the general term from xUnit Patterns; "unit under test" is the common name when the SUT is one unit.
What are the three steps of TDD?
The three steps are red, green and refactor. Write a test that fails, write the simplest code that makes it pass, then improve the design while keeping every test passing.
What is the difference between a mock and a stub?
A stub returns canned answers so the unit under test can run, while a mock also checks that the unit made the expected calls. Use a stub to feed input and a mock when the call itself is the behavior.
Does TDD slow down development?
TDD adds time when you write each feature, because tests come first. In return you get a regression suite as you go and can refactor safely; whether that saves time overall depends on how long the code lives.
Can AI write tests for TDD?
Yes, an AI coding agent can draft tests from a test list you write or review. Keep the red step, and never let the agent change or delete assertions to make failing code pass.