Lesson 41 of 45 · Testing as a Discipline
Test-Driven Development
The most religious topic in software
There are two ways to talk about TDD. The first is religious: TDD is the One True Way, all serious developers do it, and any code written without writing a test first is morally suspect. The second is dismissive: TDD is overhead, slows you down, and produces tests that lock in implementation details.
Both versions are wrong: TDD is neither salvation nor wasted effort, but a workflow with a specific shape, specific benefits, and specific costs. The honest version of the practice in the codebases I've worked on is TDD some of the time, in places where it earns its keep, with a clear sense of when it doesn't.
What TDD actually is
Kent Beck described TDD in Test-Driven Development: By Example (2002). The core loop has three steps:
Red. Write a failing test for the smallest piece of behavior you want next. Run it. Confirm it fails for the reason you expect.
Green. Write the simplest production code that makes the test pass. Don't worry about elegance; just get to green.
Refactor. With the green test as your safety net, clean up. Rename, extract, simplify. Re-run the test to confirm you didn't break anything.
Repeat. Each cycle is small (often minutes). The discipline is to keep the steps separate: don't write production code while the test is missing or passing; don't refactor while a test is red.
What TDD actually buys you
Three concrete things, when the practice fits the situation:
Design feedback in a tight loop. The test forces you to use the code from the outside before you build it. If using it is awkward (six dependencies, three setup steps, hard-to-mock collaborators), you discover that before you write the code, when changing the design is cheap. The first lesson of this chapter made the case that hard-to-test code is hard-to-use code. TDD turns that feedback into a practice.
Courage to refactor. The green test is a license. You can rename, restructure, extract, and inline freely; if the test still passes, the behavior is preserved. Without tests, refactoring carries fear. With them, refactoring is part of the rhythm.
A regression net for the part you wrote. Not for the whole system, not for cases you didn't think of. Just for the specific behaviors you encoded. That's a smaller benefit than people advertise, but it's real.
What TDD doesn't buy you, and shouldn't be advertised as buying you:
Provably correct code. The tests are still as good as the cases you wrote.
Coverage of edge cases you didn't think of. TDD doesn't read minds.
A free pass on integration testing. Unit-level TDD doesn't catch interaction bugs.
Universally faster development. The cycle takes time. You earn it back during refactor and debugging; you spend it during the initial write.
A small worked cycle
Imagine you need a Money value object that supports addition with currency safety. The example builds a subset of the Money class from earlier in the course: three behaviors, ending in the shape Lesson 5 of this course gives it (the full class there also has fromDollars, zero, multiplyBy and more). Currency::usd() and Currency::eur() are the named constructors from the Named Constructors lesson, and MismatchedCurrencies is the exception class from the Value Objects lesson.
Red. Write the failing test:
<?php
declare(strict_types=1);
namespace Tests\Billing;
use App\Billing\Currency;
use App\Billing\Money;
use PHPUnit\Framework\TestCase;
final class MoneyTest extends TestCase
{
public function test_adding_two_amounts_in_the_same_currency_returns_the_sum(): void
{
$a = Money::fromCents(100, Currency::usd());
$b = Money::fromCents(250, Currency::usd());
$result = $a->add($b);
$this->assertSame(350, $result->amountInCents);
}
}Run it. It fails because Money doesn't exist yet. Good.
Green. Write the simplest code that passes:
<?php
declare(strict_types=1);
namespace App\Billing;
final readonly class Money
{
public function __construct(public int $amountInCents, public Currency $currency) {}
public static function fromCents(int $cents, Currency $currency): self
{
return new self($cents, $currency);
}
public function add(Money $other): Money
{
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
}Run the test. Green.
Refactor. Nothing to clean up yet: one method, no duplication.
Red. Next case: adding different currencies should throw. The test goes into the same MoneyTest class:
<?php
declare(strict_types=1);
namespace Tests\Billing;
use App\Billing\Currency;
use App\Billing\Exceptions\MismatchedCurrencies;
use App\Billing\Money;
use PHPUnit\Framework\TestCase;
final class MoneyTest extends TestCase
{
public function test_adding_two_amounts_in_the_same_currency_returns_the_sum(): void
{
$a = Money::fromCents(100, Currency::usd());
$b = Money::fromCents(250, Currency::usd());
$result = $a->add($b);
$this->assertSame(350, $result->amountInCents);
}
public function test_adding_amounts_in_different_currencies_throws(): void
{
$a = Money::fromCents(100, Currency::usd());
$b = Money::fromCents(100, Currency::eur());
$this->expectException(MismatchedCurrencies::class);
$a->add($b);
}
}Run it. It fails (the current add doesn't check). Good.
Green. Add the check:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
final readonly class Money
{
public function __construct(public int $amountInCents, public Currency $currency) {}
public static function fromCents(int $cents, Currency $currency): self
{
return new self($cents, $currency);
}
public function add(Money $other): Money
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
}Run both tests. Green.
Refactor. The currency check sits in the middle of add, and the next operation that combines two amounts will need the same check. Extract it into a private method and run both tests again. They stay green, because the behavior did not change:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
final readonly class Money
{
public function __construct(public int $amountInCents, public Currency $currency) {}
public static function fromCents(int $cents, Currency $currency): self
{
return new self($cents, $currency);
}
public function add(Money $other): Money
{
$this->assertSameCurrency($other);
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
private function assertSameCurrency(Money $other): void
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
}
}Red. Third case: a negative amount should be rejected. Add it to MoneyTest:
<?php
declare(strict_types=1);
namespace Tests\Billing;
use App\Billing\Currency;
use App\Billing\Exceptions\MismatchedCurrencies;
use App\Billing\Money;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
final class MoneyTest extends TestCase
{
public function test_adding_two_amounts_in_the_same_currency_returns_the_sum(): void
{
$a = Money::fromCents(100, Currency::usd());
$b = Money::fromCents(250, Currency::usd());
$result = $a->add($b);
$this->assertSame(350, $result->amountInCents);
}
public function test_adding_amounts_in_different_currencies_throws(): void
{
$a = Money::fromCents(100, Currency::usd());
$b = Money::fromCents(100, Currency::eur());
$this->expectException(MismatchedCurrencies::class);
$a->add($b);
}
public function test_a_negative_amount_is_rejected(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Money cannot be negative');
Money::fromCents(-1, Currency::usd());
}
}Run it. It fails, because fromCents(-1, ...) currently builds a Money without complaint. Good.
Green. Check the amount in the constructor:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
use InvalidArgumentException;
final readonly class Money
{
public function __construct(public int $amountInCents, public Currency $currency)
{
if ($amountInCents < 0) {
throw new InvalidArgumentException('Money cannot be negative');
}
}
public static function fromCents(int $cents, Currency $currency): self
{
return new self($cents, $currency);
}
public function add(Money $other): Money
{
$this->assertSameCurrency($other);
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
private function assertSameCurrency(Money $other): void
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
}
}Run all three tests. Green.
Refactor. Every test builds a Money through fromCents, so the constructor no longer needs to be public. Make it private, which is how Lesson 5 locks the class down, and run the tests again:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
use InvalidArgumentException;
final readonly class Money
{
private function __construct(public int $amountInCents, public Currency $currency)
{
if ($amountInCents < 0) {
throw new InvalidArgumentException('Money cannot be negative');
}
}
public static function fromCents(int $cents, Currency $currency): self
{
return new self($cents, $currency);
}
public function add(Money $other): Money
{
$this->assertSameCurrency($other);
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
private function assertSameCurrency(Money $other): void
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
}
}The cycle is small and fast, and it produces a class that covers the behaviors that mattered enough to write tests for. The design fell out of using the class from the outside before building it.
When TDD earns its place
The practice fits well when:
The behavior is well-defined. "Money adds two same-currency amounts" is a clear, testable behavior. TDD has something concrete to drive toward.
The unit is small and pure. Value objects, domain entities, calculators, validators. Things that can be tested in pure PHP without booting the framework. The cycle stays fast.
The cost of a wrong design is high. Domain rules and invariants benefit from having tests first, because the tests document the intended behavior in code.
You're working in unfamiliar territory. TDD's tight loop is a way to learn the problem by doing. Each cycle teaches you something about the API.
When it doesn't
TDD doesn't fit every situation. Honest cases where it's the wrong tool:
Exploration. When you don't yet know what the code should do, writing the test first is putting the cart before the horse. Spike, learn, then come back and TDD the design that emerged.
UI work. Much of UI work is "does this look right?" which automated tests don't capture well. End-to-end smoke tests cover the critical paths; the visual side is human work.
Framework integration. Setting up a Laravel facade, configuring a service provider, writing a migration (in Symfony: a
services.yamldefinition or a Doctrine migration). There's not much "behavior" to drive; the work is mostly configuration.Throwaway scripts. A one-off Artisan command (or Symfony console command) that runs once and gets deleted. The TDD overhead doesn't pay back.
The bigger pattern: TDD pays off in the parts of the codebase that have behavior worth testing. It's overhead in the parts that don't.
The test-after alternative
Plenty of developers don't do strict TDD but write tests during or right after they write the code. This is test-after development, and it's a real practice with real benefits:
You still get a regression net.
You can write the design first, then add tests once the shape stabilizes.
Some kinds of code (exploratory, integration-heavy) work better this way.
The risks of test-after:
"Right after" easily becomes "tomorrow", which becomes "next sprint", which becomes "never". The discipline has to be real.
Tests written after the implementation can end up confirming the implementation rather than challenging it. You wrote it; of course you think it works that way.
It's harder to use the tests for design feedback. The design is already there.
The honest version, in my experience: mix the two. Critical domain logic gets TDD'd. Glue code, framework wiring, and exploratory work gets tested after. The skill is knowing which parts deserve which treatment.
Misreadings and pitfalls
"TDD means 100% coverage." It doesn't. TDD means "the code that exists exists because a test demanded it". That's a different shape than "every line is covered".
"TDD eliminates the need for design thinking." The tests don't tell you what the right architecture is; you have to bring that yourself.
"Write the test first" means literally typing the test before any thought about the production code. You think about the design first, sketch it in your head, then write the test. The test is the encoded version of the next small step you've decided to take.
Tests that mirror the production code. The TDD cycle can produce tests that lock in the exact structure of the implementation. When that happens, refactor breaks tests even when behavior didn't change. Write tests against behavior, not against implementation.
Skipping refactor. Martin Fowler's TDD article puts it this way: "The most common way that I hear to screw up TDD is neglecting the third step." You write the test, get it green, ship the green code without cleaning up. The codebase fills up with the simplest-thing-that-could-work versions of every method. Refactor is where TDD pays you back; skipping it forfeits the benefit.
Tests that are too small. TDD-ing every getter and setter individually buries the suite in micro-tests that test PHP, not your code. Test at the unit of behavior, which is usually a few methods working together, not each property in isolation.
TDD-ing everything regardless of fit. The practice has costs. Writing tests first for code where the behavior is "wire this framework feature" produces tests that don't help anyone. Pick TDD for the parts where it earns its place.
The one thing to remember
TDD is a workflow of small failing test, just enough code, then cleanup, and it earns its place in domain-heavy code with well-defined behavior.
Related Links
- Test Driven Development: By ExampleThe publisher page for Kent Beck's original 2002 book, the source of the red-green-refactor cycle this lesson walks through.
- Test Driven DevelopmentMartin Fowler's short explanation of the same red-green-refactor cycle and why skipping the refactor step causes problems.
- PHPUnit ManualThe official PHPUnit documentation for the assertions and test structure used in the worked examples.