Skip to content

Lesson 39 of 45 · Testing as a Discipline

The Testing Pyramid: Unit, Integration and End-to-End Tests

Intermediate•
lesson•
November 7, 2026•
~10 min read

The test suite nobody runs

You join a team. The first thing the senior engineer warns you about is the test suite. "It's slow. Don't run it locally; let CI do it. And don't worry if a few are flaky. We just rerun them."

You shrug, accept the deal, and join the teams that have stopped trusting their tests. The suite "passes" in the sense that CI eventually goes green. It "covers" the code in the sense that a coverage tool reports a number. It does not catch bugs reliably, it does not give the team confidence to refactor, and nobody runs it during development. The tests exist; the testing doesn't.

This chapter is about the difference. The next five lessons cover specific tools (test doubles, TDD, BDD, mutation testing and refactoring) and this opening lesson is the foundation: what tests are for, what they aren't, and the shape of a suite that actually works.

What tests are for

Tests do three things in a healthy codebase:

  • They give the team confidence to change code. A green suite, on the part of the system you're touching, is a license to refactor. Without it, every change carries fear.

  • They surface design problems early. A function that needs five collaborators stubbed and a database booted is doing too much.

  • They document intent. A well-named test reads like a sentence about the system: "quotes a reservation at the configured price". Tests are sometimes the most readable specification of what the code is supposed to do.

Notice what's not on this list:

  • "They prove the code is correct." Tests can prove specific scenarios work, but they can't prove the absence of bugs.

  • "They catch every regression." Tests catch the regressions you wrote tests for. Bugs that fall in the gaps still ship.

  • "They replace thinking." A passing suite isn't a substitute for understanding the change you made.

The kinds of tests

A few categories are worth naming, because the trade-offs differ:

Unit tests exercise one class or one small group of classes in isolation, with collaborators replaced by stand-ins, called test doubles (the next lesson names the kinds). They run in milliseconds. They don't touch the database, the file system, the network, or the framework. They tell you whether a specific piece of logic does what you think.

The Money value object from the Named Constructors lesson needs no doubles at all. MismatchedCurrencies comes from the Value Objects lesson. The test builds two values, adds them and checks the result, and it extends PHPUnit's own TestCase, so no framework boots:

PHP
<?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 MoneyAdditionTest extends TestCase { public function test_adding_two_amounts_in_the_same_currency_sums_the_cents(): void { $roomRate = Money::fromCents(12000, Currency::usd()); $cleaningFee = Money::fromCents(3500, Currency::usd()); $total = $roomRate->add($cleaningFee); $this->assertTrue($total->equals(Money::fromCents(15500, Currency::usd()))); } public function test_adding_two_currencies_is_refused(): void { $usd = Money::fromCents(12000, Currency::usd()); $eur = Money::fromCents(3500, Currency::eur()); $this->expectException(MismatchedCurrencies::class); $usd->add($eur); } }

Integration tests exercise a slice of the system with real collaborators: a real database, a real cache, real queue, real file system. They are slower than unit tests. They tell you whether the pieces actually work together.

This test runs EloquentReservations from the Repository Pattern lesson against a real database. It saves a reservation, loads it back by id and compares the values. That lesson names ReservationModel and never shows it, so here it is: an Eloquent model with a string primary key, because ReservationId wraps a UUID, and no timestamp columns, because save() writes none.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; final class ReservationModel extends Model { use HasFactory; protected $table = 'reservations'; public $incrementing = false; public $timestamps = false; protected $keyType = 'string'; }

The migration creates the columns save() writes. Ids are 36-character strings, dates are date columns, the cents are an unsigned integer and the status is a short string holding the enum's backing value:

PHP
<?php declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('reservations', function (Blueprint $table): void { $table->string('id', 36)->primary(); $table->string('guest_id', 36); $table->unsignedInteger('room_id'); $table->date('check_in'); $table->date('check_out'); $table->unsignedSmallInteger('adults'); $table->unsignedSmallInteger('children'); $table->unsignedInteger('price_cents'); $table->string('currency', 3); $table->string('status', 20); }); } public function down(): void { Schema::dropIfExists('reservations'); } };

RefreshDatabase runs that migration and gives each test a clean database:

PHP
<?php declare(strict_types=1); namespace Tests\Reservations; use App\Billing\Currency; use App\Billing\Money; use App\Booking\GuestCount; use App\Booking\GuestId; use App\Booking\RoomId; use App\Reservations\DateRange; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Reservation; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use Carbon\CarbonImmutable; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; final class EloquentReservationsTest extends TestCase { use RefreshDatabase; public function test_a_saved_reservation_comes_back_with_the_same_values(): void { $repository = new EloquentReservations(); $reservation = Reservation::request( guestId: GuestId::next(), roomId: new RoomId(14), stayDates: new DateRange( CarbonImmutable::parse('2026-05-06'), CarbonImmutable::parse('2026-05-09'), ), guestCount: new GuestCount(adults: 2, children: 1), quotedPrice: Money::fromCents(42000, Currency::usd()), ); $repository->save($reservation); $found = $repository->withId($reservation->id); $this->assertSame($reservation->id->value, $found->id->value); $this->assertSame(3, $found->stayDates->nights()); $this->assertTrue($found->quotedPrice->equals($reservation->quotedPrice)); $this->assertSame(ReservationStatus::Pending, $found->status()); } public function test_an_unknown_id_is_reported_as_not_found(): void { $this->expectException(ReservationNotFound::class); (new EloquentReservations())->withId(ReservationId::next()); } }

In Symfony the same test is a KernelTestCase that gets Reservations from static::getContainer(), with DAMA DoctrineTestBundle rolling back each test.

End-to-end tests exercise the system through the same interface a user does: an HTTP request goes in, real responses come out, every layer is real. They are the slowest. They tell you whether the deployed system behaves like a system.

Symfony has a base class for each of the last two kinds. KernelTestCase boots the kernel and gives the test the service container, which makes it the integration test base. WebTestCase adds createClient(), which sends requests through the kernel and returns the response, which makes it the end-to-end base.

Other names appear in the literature: feature tests, acceptance tests, contract tests, characterization tests. They're variations on the three above, with different scope or different audience. The terminology fights are not worth getting into; the trade-offs (speed, isolation, breadth) are what matter.

The pyramid (or trophy)

The shape of a healthy test suite has been argued about for years. Two main visions:

The testing pyramid (Mike Cohn): lots of fast unit tests, fewer integration tests, even fewer end-to-end tests. Each layer covers what's below it less expensively.

A pyramid in three layers. The wide base is unit tests (many), the middle layer is integration tests (some), and the narrow top is end-to-end tests (few).

The testing trophy (Kent C. Dodds): more integration tests than unit tests, because integration tests catch more real bugs per unit of effort, with unit tests for tricky logic and end-to-end tests for the most critical paths. It also adds a base layer the pyramid lacks, static analysis, which catches typos and type errors before any test runs; the trophy diagram on Dodds' site labels its four sections End to End, Integration, Unit and Static.

Both have a point, and the right mix depends on the domain:

  • For codebases with rich domain logic (rich models, value objects, complex rules): unit tests of the domain pay off enormously. They run in milliseconds, they cover a lot of ground, and they enable fearless refactoring of the rules. Pyramid-shaped, with a thick base.

  • For codebases that are mostly orchestration (handlers calling repositories calling external services): integration tests are more useful, because the bugs live in the seams between components, not inside any one component. Trophy-shaped.

  • In the codebases I've worked on, a mix. Unit tests for the domain, integration tests for use cases, a small number of end-to-end smoke tests for critical paths.

The dogmatic version of either ends up wasting effort. Pure-unit suites miss integration bugs. Pure-integration suites are slow, flaky, and expensive to debug. The answer is to pick the right kind of test for the kind of bug each layer is most likely to ship.

What tests are NOT for

A few things teams use tests for that they shouldn't:

A coverage number. "We have 80% coverage." Coverage measures whether lines were executed by some test. It says nothing about whether the right things were checked, whether assertions were meaningful, or whether the test would catch a real bug. A high-coverage suite that doesn't catch bugs is worse than a smaller suite that does. The question is whether a test caught the regression it was written for, and mutation testing is a much sharper signal for that.

Punishing developers for bugs. Tests are not a moral instrument. A bug in production means no test covered that case, or the test asserted the wrong thing. The fix is to write the test now and prevent recurrence.

Replacing manual QA. Some interaction patterns (visual layout, accessibility, performance under load, real user behavior) are hard to capture in automated tests. Manual QA still matters. Tests cover the parts they can; humans cover the rest.

Encoding implementation details. A test that asserts "method X calls method Y three times with these arguments" is testing the implementation. Refactoring the implementation breaks the test even when the behavior didn't change. Behavior-focused tests survive refactors; implementation-focused tests don't. The next lesson shows the same behavior checked both ways.

Tests as design feedback

The best argument for tests, beyond catching bugs, is that they're a design feedback loop.

Hard-to-test code is hard-to-use code. A method that needs five mocks, a frozen clock, three pre-loaded models, and a configured queue to test is a method that's doing too many things.

When you write a test and it feels heavy, change the design before you change the test. Pull the dependencies into the constructor. Split the method. Move the rule into a value object. The test gets simpler because the code got simpler.

This is one of the original arguments for TDD: writing the test first forces you to use the code from the outside, which surfaces design problems before they're baked in. Even without strict TDD, the same feedback applies: pay attention when tests get hard, because that's the design talking.

PHP-specific notes

A few practical points:

PHPUnit. The standard test framework in modern PHP. Class-based, with an explicit setup/teardown structure. This course uses PHPUnit throughout. Other frameworks exist; the patterns in this chapter are framework-agnostic and translate with minor syntax changes.

RefreshDatabase. Laravel's RefreshDatabase trait keeps tests from leaking data into each other. Per the Laravel 13.x docs, it does not migrate the database if the schema is up to date; it runs each test inside a database transaction instead. The DatabaseMigrations and DatabaseTruncation traits reset the database fully, and the docs call both "significantly slower". In Symfony, the dama/doctrine-test-bundle package (version 8.7.0 on Packagist allows symfony/framework-bundle ^8.0) wraps each test in a transaction the same way.

#[Test] attributes. PHPUnit supports #[Test] attributes as an alternative to the test_ method prefix. Examples in this course use both; pick one convention in your own suite and stick with it.

Factories. Eloquent factories (ReservationModel::factory()->create()) generate realistic test data. This is the Eloquent factory (a testing helper), not the Factory Pattern. The HasFactory trait on the model above looks for Database\Factories\Reservations\Models\ReservationModelFactory, and that factory has to fill the string id and guest_id, because the table doesn't generate them. Use them liberally for integration tests; they're one of Laravel's strongest features. The Symfony counterpart is zenstruck/foundry, which supports Symfony 8 and builds Doctrine entities from factories.

Parallel runs. php artisan test --parallel runs the suite across several processes, and needs the brianium/paratest package installed as a dev dependency (composer require brianium/paratest --dev). Speed matters; a slow suite stops being run, and a suite that isn't run isn't a test suite.

Pitfalls

A few common mistakes:

Tests that are larger than the change. When a one-line change needs edits in five test files, the tests are coupled to the implementation. Test through public behavior, so changing how something works doesn't touch the tests for what it does.

Flakiness tolerated as a fact of life. A flaky test is a broken test. Either the test is wrong, or the code under test is non-deterministic. Both are bugs. "Just rerun it" is the team giving up, and once that's the policy, the suite stops being trusted.

Treating tests as throwaway. "We'll just delete this test if it gets in the way" is the start of a death spiral. Tests are part of the codebase. They get refactored, named carefully, reviewed in PRs, and maintained. Treating them as second-class produces second-class tests.

The one thing to remember

Write the tests that catch real regressions. Skip the tests that exist for show. Trust the suite enough to run it during development, and refactor it when it starts to lie.

Course Content