Lesson 10 of 15 · Living With an Architecture
Testing Across the Boundary
The suite that got slower
A team rebuilt their booking module around ports and adapters, the shape the Hexagonal Architecture lesson walked through: a Reservations port, EloquentReservations behind it, a command handler in the middle that never imports Eloquent. The architecture was right and the test suite still got slower, not faster, because every test they wrote kept doing what it had always done: extend the framework's test case, boot the container, hit a real database.
The rule "a room with an active overlapping reservation cannot take another one" ended up asserted three times. A feature test posted to /reservations, booted the whole application, and checked for a 422 response. A controller test built a Mockery double of the Reservations port and asserted save() was never called. A handler test, the only one of the three that should have existed, built the command handler against an in-memory fake and asserted the handler threw. All three tested the same rule, at three different speeds, and the two slower ones paid full framework-boot price to reconfirm what the fastest one already proved. Meanwhile the one thing that never got tested was whether EloquentReservations actually behaves the way the in-memory fake promised it would.
Drawing a boundary between the core and its adapters does not by itself make a test suite faster. It answers a question the team hadn't been asking: which test belongs on which side of that line. Get the answer wrong, and the boundary just gives you more places to write the same slow test.
Three kinds of test, three positions on the boundary
Once a port and an adapter exist, three different things can be under test, and each one has exactly one honest way to test it.
Use case tests run against fakes and never boot the framework. They construct the handler directly, hand it a fake for every port, call handle(), and assert on what the fake recorded or what exception came back. This is where business rules live, and it's where they get tested, because this is the one place they're expressed in plain PHP with nothing else in the way.
Four ports do the work here, all from the Hexagonal Architecture lesson: Reservations, Rooms, Clock and Dispatcher. The one the tests lean on most:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Reservation;
use Hearth\Booking\DateRange;
use Hearth\Booking\RoomId;
interface Reservations
{
public function withId(ReservationId $id): Reservation;
public function save(Reservation $reservation): void;
/** @return list<Reservation> */
public function overlapping(RoomId $roomId, DateRange $stayDates): array;
}The command and the handler, the same ones the Hexagonal Architecture lesson built. ReservationPriceFactory::build() is the simplified three-argument form from the Request Lifecycle lesson, and it has no constructor dependencies:
<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\RoomId;
final readonly class RequestReservationCommand
{
public function __construct(
public GuestId $guestId,
public RoomId $roomId,
public DateRange $stayDates,
public GuestCount $guestCount,
) {}
}<?php
declare(strict_types=1);
namespace Hearth\Booking\RequestReservation;
use Hearth\Booking\Clock;
use Hearth\Booking\Dispatcher;
use Hearth\Booking\Reservation\CancellationPolicy;
use Hearth\Booking\Reservation\Reservation;
use Hearth\Booking\Reservation\ReservationId;
use Hearth\Booking\Reservation\Reservations;
use Hearth\Booking\Reservation\RoomNotAvailable;
use Hearth\Booking\ReservationPriceFactory;
use Hearth\Booking\Rooms;
final readonly class RequestReservationCommandHandler
{
public function __construct(
private Reservations $reservations,
private Rooms $rooms,
private ReservationPriceFactory $priceFactory,
private CancellationPolicy $cancellationPolicy,
private Clock $clock,
private Dispatcher $dispatcher,
) {}
public function handle(RequestReservationCommand $command): ReservationId
{
$room = $this->rooms->withId($command->roomId);
if ($this->reservations->overlapping($command->roomId, $command->stayDates) !== []) {
throw new RoomNotAvailable($command->roomId, $command->stayDates);
}
$reservation = Reservation::request(
guestId: $command->guestId,
roomId: $command->roomId,
stayDates: $command->stayDates,
guestCount: $command->guestCount,
totalPrice: $this->priceFactory->build($room, $command->stayDates, $command->guestCount),
cancellationPolicy: $this->cancellationPolicy,
requestedAt: $this->clock->now(),
);
$this->reservations->save($reservation);
foreach ($reservation->releaseEvents() as $event) {
$this->dispatcher->dispatch($event);
}
return $reservation->id;
}
}Every fake and test in this lesson lives in the Booking module's Tests/ folder, in the Hearth\Booking\Tests namespace:
Hearth/Booking/Tests/
├── InMemoryReservations.php # fake
├── InMemoryRooms.php # fake
├── FixedClock.php # fake
├── RecordingDispatcher.php # spy
├── ReservationFactory.php # test data
├── RequestReservationCommandHandlerTest.php # use case test
├── EloquentReservationsMappingTest.php # adapter test
├── RequestReservationEndToEndTest.php # end-to-end test
├── ReservationsContractTest.php # contract
├── InMemoryReservationsTest.php # fake contract
└── EloquentReservationsTest.php # adapter contractPHPUnit finds them through a third test suite in phpunit.xml, next to the two Laravel ships with:
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
<testsuite name="Modules">
<directory>Hearth/*/Tests</directory>
</testsuite>
</testsuites>Nothing in the core imports Eloquent, HTTP, or a container, and the test that exercises it needs none of them either. Here's a fake for a repository, filtered by room and skipping cancelled reservations. withId() throws the same ModelNotFoundException the adapter's findOrFail() does, so callers see one failure either way, and that exception class is the only Eloquent import the fake needs:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\DateRange;
use Hearth\Booking\Reservation\Reservation;
use Hearth\Booking\Reservation\ReservationId;
use Hearth\Booking\Reservation\Reservations;
use Hearth\Booking\Reservation\ReservationStatus;
use Hearth\Booking\RoomId;
use Illuminate\Database\Eloquent\ModelNotFoundException;
final class InMemoryReservations implements Reservations
{
/** @var array<string, Reservation> */
private array $reservations = [];
public function withId(ReservationId $id): Reservation
{
return $this->reservations[$id->toString()] ?? throw new ModelNotFoundException("No reservation {$id->toString()}");
}
public function save(Reservation $reservation): void
{
$this->reservations[$reservation->id->toString()] = $reservation;
}
public function overlapping(RoomId $roomId, DateRange $stayDates): array
{
return array_values(array_filter(
$this->reservations,
static fn (Reservation $reservation): bool => $reservation->roomId->equals($roomId)
&& $reservation->status !== ReservationStatus::CANCELLED
&& $reservation->stayDates->overlaps($stayDates),
));
}
}A fake for Rooms, a fake for Clock and a spy for Dispatcher, each small enough to write inline in most suites:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\Room;
use Hearth\Booking\RoomId;
use Hearth\Booking\Rooms;
final class InMemoryRooms implements Rooms
{
/** @var array<string, Room> */
private array $rooms = [];
public function add(Room $room): void
{
$this->rooms[$room->id->toString()] = $room;
}
public function withId(RoomId $id): Room
{
return $this->rooms[$id->toString()];
}
}<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Carbon\CarbonImmutable;
use Hearth\Booking\Clock;
final readonly class FixedClock implements Clock
{
public function __construct(private CarbonImmutable $now) {}
public function now(): CarbonImmutable
{
return $this->now;
}
}<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\Dispatcher;
final class RecordingDispatcher implements Dispatcher
{
/** @var list<object> */
private array $dispatched = [];
public function dispatch(object $event): void
{
$this->dispatched[] = $event;
}
/** @return list<object> */
public function events(): array
{
return $this->dispatched;
}
}Test data comes from one small factory, so each test states only what makes it different:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Carbon\CarbonImmutable;
use Hearth\Booking\Currency;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\Money;
use Hearth\Booking\Reservation\FreeWindowCancellationPolicy;
use Hearth\Booking\Reservation\Reservation;
use Hearth\Booking\RoomId;
final class ReservationFactory
{
public static function make(RoomId $roomId, DateRange $stayDates): Reservation
{
return Reservation::request(
guestId: GuestId::next(),
roomId: $roomId,
stayDates: $stayDates,
guestCount: new GuestCount(adults: 2, children: 0),
totalPrice: Money::fromCents(45000, new Currency('USD')),
cancellationPolicy: new FreeWindowCancellationPolicy(),
requestedAt: CarbonImmutable::parse('2026-04-01'),
);
}
}And the tests that finally put the "room not available" rule in exactly one place:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\GuestCount;
use Hearth\Booking\GuestId;
use Hearth\Booking\RequestReservation\RequestReservationCommand;
use Hearth\Booking\RequestReservation\RequestReservationCommandHandler;
use Hearth\Booking\Reservation\FreeWindowCancellationPolicy;
use Hearth\Booking\RequestReservation\ReservationRequested;
use Hearth\Booking\Reservation\RoomNotAvailable;
use Hearth\Booking\ReservationPriceFactory;
use Hearth\Booking\Room;
use Hearth\Booking\RoomId;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
final class RequestReservationCommandHandlerTest extends TestCase
{
#[Test]
public function it_saves_the_reservation_and_dispatches_the_requested_event(): void
{
$reservations = new InMemoryReservations();
$dispatcher = new RecordingDispatcher();
$roomId = RoomId::next();
$guestId = GuestId::next();
$reservationId = $this->handler($reservations, $dispatcher, $roomId)->handle(
new RequestReservationCommand(
guestId: $guestId,
roomId: $roomId,
stayDates: $this->stayDates(),
guestCount: new GuestCount(adults: 2, children: 0),
),
);
self::assertSame(
$roomId->toString(),
$reservations->withId($reservationId)->roomId->toString(),
);
$dispatched = $dispatcher->events();
self::assertCount(1, $dispatched);
self::assertInstanceOf(ReservationRequested::class, $dispatched[0]);
self::assertSame($reservationId->toString(), $dispatched[0]->reservationId);
self::assertSame($guestId->toString(), $dispatched[0]->guestId);
self::assertSame($roomId->toString(), $dispatched[0]->roomId);
}
#[Test]
public function it_rejects_a_room_with_an_active_overlapping_reservation(): void
{
$reservations = new InMemoryReservations();
$roomId = RoomId::next();
$reservations->save(ReservationFactory::make($roomId, $this->stayDates()));
$this->expectException(RoomNotAvailable::class);
$this->handler($reservations, new RecordingDispatcher(), $roomId)->handle(
new RequestReservationCommand(
guestId: GuestId::next(),
roomId: $roomId,
stayDates: $this->stayDates(),
guestCount: new GuestCount(adults: 1, children: 0),
),
);
}
private function handler(
InMemoryReservations $reservations,
RecordingDispatcher $dispatcher,
RoomId $roomId,
): RequestReservationCommandHandler {
$rooms = new InMemoryRooms();
$rooms->add(new Room($roomId, capacity: 2));
return new RequestReservationCommandHandler(
$reservations,
$rooms,
new ReservationPriceFactory(),
new FreeWindowCancellationPolicy(),
new FixedClock(CarbonImmutable::parse('2026-05-01 09:00:00')),
$dispatcher,
);
}
private function stayDates(): DateRange
{
return new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-04'),
);
}
}A third test, not shown here, saves a reservation for the same room and dates, calls cancel() on it, and asserts the handler does not throw. Same fake, same factory.
Adapter tests run the real thing against the real dependency, and assert nothing about business rules. An adapter's job is mapping: turning a Reservation into rows and back, correctly. It has no rule of its own to get wrong; the rule already got tested against the fake. What it can get wrong is the mapping itself, and that's Eloquent's problem, not the domain's:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\Infrastructure\EloquentReservations;
use Hearth\Booking\RoomId;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
final class EloquentReservationsMappingTest extends TestCase
{
use RefreshDatabase;
#[Test]
public function it_stores_the_price_as_cents_and_a_currency_code_not_a_float(): void
{
$reservation = ReservationFactory::make(
RoomId::next(),
new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-04'),
),
);
(new EloquentReservations())->save($reservation);
$this->assertDatabaseHas('reservations', [
'id' => $reservation->id->toString(),
'total_price_cents' => 45000,
'total_price_currency' => 'USD',
]);
}
}RefreshDatabase migrates the test database once per run, then wraps each test in a transaction it rolls back at the end. This test does not ask whether a room can be double-booked. It asks whether the column that's supposed to hold cents actually holds cents.
One thin end-to-end test per slice proves the wiring holds, and nothing more. It goes through the real driving adapter (HTTP, in this case), the real handler, and the real driven adapter, and checks that a request produces a persisted row and the event the rest of the system reacts to. It does not re-check the availability rule, the pricing, or any other branch; those already have a use case test each.
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\GuestId;
use Hearth\Booking\RequestReservation\ReservationRequested;
use Hearth\Booking\RoomId;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
final class RequestReservationEndToEndTest extends TestCase
{
use RefreshDatabase;
#[Test]
public function it_persists_a_requested_reservation_and_dispatches_the_requested_event(): void
{
Event::fake([ReservationRequested::class]);
$guestId = GuestId::next()->toString();
$roomId = RoomId::next()->toString();
DB::table('rooms')->insert(['id' => $roomId, 'capacity' => 2]);
$this->postJson('/reservations', [
'guest_id' => $guestId,
'room_id' => $roomId,
'check_in' => '2026-06-01',
'check_out' => '2026-06-04',
'adults' => 2,
'children' => 0,
])->assertCreated();
$this->assertDatabaseCount('reservations', 1);
$this->assertDatabaseHas('reservations', [
'guest_id' => $guestId,
'room_id' => $roomId,
]);
Event::assertDispatched(
ReservationRequested::class,
static fn (ReservationRequested $event): bool => $event->guestId === $guestId
&& $event->roomId === $roomId,
);
}
}The test seeds the rooms row that Booking's EloquentRooms reads. The other three slices in the module (confirm, cancel, check in) each get their own, equally thin test, and none of them re-derives a rule the handler tests already cover.
The contract test: keeping the fake honest about the seam
A contract test is the way to stop a fake from lying: one abstract PHPUnit case written against an interface, extended once per implementation. InMemoryReservations and EloquentReservations both promise to satisfy Reservations. The only way to know they agree is to ask them the same question and compare the answers. Here the abstract case asserts the one query the handler depends on, overlapping(), for the two rules the handler leans on: it scopes to the room, and it ignores cancelled reservations:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Carbon\CarbonImmutable;
use Hearth\Booking\DateRange;
use Hearth\Booking\Reservation\Reservations;
use Hearth\Booking\RoomId;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
abstract class ReservationsContractTest extends TestCase
{
abstract protected function reservations(): Reservations;
#[Test]
public function it_scopes_overlapping_to_the_room_it_was_asked_about(): void
{
$stayDates = new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-04'),
);
$roomId = RoomId::next();
$inThisRoom = ReservationFactory::make($roomId, $stayDates);
$inAnotherRoom = ReservationFactory::make(RoomId::next(), $stayDates);
$reservations = $this->reservations();
$reservations->save($inThisRoom);
$reservations->save($inAnotherRoom);
$found = $reservations->overlapping($roomId, $stayDates);
self::assertCount(1, $found);
self::assertSame($inThisRoom->id->toString(), $found[0]->id->toString());
}
#[Test]
public function it_ignores_a_cancelled_reservation(): void
{
$stayDates = new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-04'),
);
$roomId = RoomId::next();
$cancelled = ReservationFactory::make($roomId, $stayDates);
$cancelled->cancel('Guest changed plans', CarbonImmutable::parse('2026-04-02'));
$reservations = $this->reservations();
$reservations->save($cancelled);
self::assertSame([], $reservations->overlapping($roomId, $stayDates));
}
}Each implementation gets a subclass that supplies itself and nothing else:
<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\Reservation\Reservations;
final class InMemoryReservationsTest extends ReservationsContractTest
{
protected function reservations(): Reservations
{
return new InMemoryReservations();
}
}<?php
declare(strict_types=1);
namespace Hearth\Booking\Tests;
use Hearth\Booking\Infrastructure\EloquentReservations;
use Hearth\Booking\Reservation\Reservations;
use Illuminate\Foundation\Testing\RefreshDatabase;
final class EloquentReservationsTest extends ReservationsContractTest
{
use RefreshDatabase;
protected function reservations(): Reservations
{
return new EloquentReservations();
}
}The abstract case extends the application's own test case, not plain PHPUnit, because the Eloquent subclass needs a booted container for RefreshDatabase. InMemoryReservationsTest pays that same boot cost even though it never touches a row. In exchange, if overlapping() is ever implemented to filter by room in one class and by room and guest in the other, this is the test that catches it, on the next run, instead of in a support ticket about a guest who somehow booked an already-taken room.
What goes where
Under test | Test kind | May touch | Roughly how fast |
|---|---|---|---|
The command handler's rules (availability, pricing, what gets dispatched) | Use case test, against fakes for every port | Fakes only | Milliseconds |
The adapter's mapping (columns, types, casts) | Adapter test, against the real dependency | The real database, inside a rolled-back transaction | Milliseconds to low seconds |
The shared behaviour every implementation of a port must honor | Contract test, run once per implementation | Fake: nothing beyond the booted container. Real adapter: the real database | Both pay a container boot; the adapter adds database time |
The path from driving adapter to driven adapter | One thin end-to-end test per slice | A booted container, the real route, the real database | Seconds |
"Milliseconds" is for a test built from plain objects and an array, "seconds" for a test that boots a container and resolves a route. Time your own suite before trusting either number for your own module.
Where the duplicate coverage comes from
The suite that opened this lesson had two recurring shapes.
A business rule asserted again in a feature test.
RequestReservationEndToEndTestgrows a second test method for "room not available", withRefreshDatabaseand a real HTTP call, duplicating a rule the handler test already covers in a fraction of the time.The port mocked in a controller test, and the mock asserted on.
$mock->shouldReceive('save')->once()tests that a method got called, not that a reservation exists afterward. It's the usual mocking trade, applied at the seam: a refactor that reaches the same outcome a different way breaks a test that was never checking the outcome.
Pitfalls
A contract test extended exactly once. Writing ReservationsContractTest and only ever creating InMemoryReservationsTest, because wiring up the Eloquent subclass takes a working database connection, produces a contract test that guards nothing. The whole benefit comes from running the identical assertions against both sides; one side alone is just a slower unit test.
Business rules creeping into the adapter test. The data is already there, the test is already querying the row, and it's tempting to add one more assertion checking that a cancelled reservation's refund amount landed correctly. Now the refund rule is tested at database speed too, and the adapter test and the handler test can quietly disagree about what the rule actually is.
Reading a passing contract test as proof the adapter has no bugs left. A contract test only checks what the interface promises. An index that's missing, a query that's slow under load, a connection pool that's misconfigured: none of that is visible to an assertion that only checks the returned values are correct.
The one thing to remember
A hexagonal boundary tells you which test to write on each side of it: fakes for the core, the real dependency for the adapter, one thin path through both for the wiring, and a contract test to keep the fake from quietly drifting away from what the real adapter does. A suite without the contract test can be slow and still miss the bug.
Related Links
- Test Pyramid, Martin Fowlerthe argument for many fast low-level tests and few slow high-level ones.
- Mocks Aren't Stubs, Martin Fowlerthe distinction between testing outcomes and testing calls, behind why the adapter test and the contract test assert on state, not on interactions.
- Database Testing, Laravel 13.xthe current documentation for RefreshDatabase, assertDatabaseHas, and assertDatabaseCount, used throughout this lesson's adapter and end-to-end tests.