Testing DDD code in Symfony: unit tests of the domain layer, InMemory repositories, integration tests with Doctrine, functional API tests, domain event tests, and architecture tests.
In DDD, the domain layer depends on neither the framework nor the database, so it can be tested directly from PHPUnit
without booting the Symfony kernel. That is the main practical difference from traditional layered architectures,
where unit tests need the container and each of them pays for the bootstrap. Without the kernel, a single test is an
order of magnitude faster, and the whole domain suite is worth running after every change, not only in CI. The building
blocks of the domain layer are described in the DDD Building Blocks chapter: entities, value objects,
aggregates, and domain events.
FIG. 17.1-ATest pyramid for a DDD application – the ratio and content of each layer
Test pyramid for DDD
The test pyramid (a concept popularized by Mike Cohn in Succeeding with Agile, 2009
[1])
splits a test suite into three layers. They differ in speed, in the degree of isolation, and in how much code a single test covers:
The ratio of layers is not a constant
The pyramid says there should be fewer slow tests than fast ones. It does not say in what ratio. Fowler therefore
contrasts it with the ice-cream cone: a suite dominated by slow tests through the UI. It falls apart for three
reasons: the build takes a long time, a small change to the system breaks many tests at once, and running headless in a pipeline
is problematic [2]. Ham Vocke keeps the shape of the pyramid,
but the names of Cohn's layers do not matter to him. He insists on two things: tests should have different
granularity, and the higher up the pyramid, the fewer of them there should be. He takes integration tests narrowly – each one verifies
a single integration point and replaces the rest with test doubles [3].
For a DDD project, this yields a rule of thumb: the center of gravity of the suite follows the thickness of the domain logic. A Bounded Context
with a rich model can carry a wide base of unit tests. A context that only translates HTTP requests
into database queries has no such base, and integration tests carry its safety net. Kent C. Dodds builds on the same
reasoning with the Testing Trophy alternative, which puts the largest investment into the integration layer
[4]. It is formulated
for JavaScript, but the question of how much logic is actually tested in isolation applies to PHP too.
Unit tests of the domain layer cover the largest share of the code and run in milliseconds. All they need is
PHPUnit and the domain classes themselves; they need no kernel, database, or fixtures.
The examples in this chapter target PHPUnit 13 and PHP 8.4. This time the version matters more than usual. PHPUnit 12
removed support for metadata in doc comments, so @dataProvider, @covers, @test, and @group are no
longer instructions for the framework – they remain ordinary comments. Metadata is written with attributes from the
PHPUnit\Framework\Attributes namespace: #[DataProvider], #[TestWith], #[CoversClass], #[Group], #[Test][5]. A test with @dataProvider carried over from a tutorial for
PHPUnit 9 ends with an error about a missing method argument. @test is trickier: a method without the test prefix
silently stops running.
Testing value objects
A value object test verifies three things: invalid input throws the corresponding exception, two instances
with the same value are equal via equals(), and the object stays immutable – a different value means
a new instance.
Named keys in the data provider show up in the PHPUnit output, so a failing case is visible
without reading the test: EmailTest::testThrowsExceptionForInvalidInput@missing domain with data ('jan@').
For one or two inputs, the #[TestWith([''])] attribute directly above the method is enough; a separate
provider pays off from three cases upward.
Testing entities
An entity test verifies what the entity does, not what its properties look like. It calls a public method, checks
the resulting state through other public methods, and, for forbidden operations, expects a specific domain exception.
Accessing private properties through reflection is a sign that the test follows the implementation instead of the behavior.
Testing aggregates
An aggregate protects the consistency of a group of entities and emits domain events. An aggregate test therefore verifies
two things: the transactional invariants (rules that hold for the whole aggregate after every operation) and that
the operation emitted the expected events in the right order.
Domain events are how an aggregate talks to the rest of the system. A test therefore verifies directly what
the aggregate emits after an operation: the event type, its data, and the order within a single transaction. Relying on
a side effect of the event dispatcher is brittle and adds a needless dependency to a unit test. For systems
that use events as the source of truth, the Event Sourcing chapter describes complementary strategies
for testing auditability and projection rebuilds.
Given-when-then over an event stream
In an event-sourced aggregate, the state is derived from history, so the test is written differently. The input is not
a constructor but a stream of events: given is the history, when is the call of a domain method, and then
is the events recorded by exactly that operation. The EventSourcedAggregate base class with the recordEvent()
and reconstituteFromEvents() methods is defined in the
PHP: the EventSourcedAggregate base class section of the Event Sourcing chapter.
Reconstruction from history applies the state but records nothing – releaseEvents() returns an empty array afterward.
The assertion therefore relates only to what the tested operation added.
The second test guards a rule that weighs more here than in a state-stored aggregate: a failed operation must not
leave an event in the buffer. In an event-sourced aggregate, the events are the state itself. If confirm() recorded OrderConfirmed
before checking the invariant, the repository would write the event to the stream on the next save, and the history would claim something that never happened.
A test double is the general name for a replacement of a real dependency in a test. The taxonomy of five types – dummy, stub,
spy, mock, and fake – was introduced by Gerard Meszaros in xUnit Test Patterns: Refactoring Test Code
(Addison-Wesley, 2007) [6]; Fowler brought it to wider attention with the article
Mocks Aren't Stubs[7]. With PHPUnit you work
mainly with four of them (stub, mock, fake, spy). Each leads to a different style of test and a different resilience
to refactoring.
Behind this recommendation stands Fowler's distinction between two styles of verification. State verification checks
the state of the system after an action; behavior verification checks that the expected calls to collaborators took place.
Of the five types of doubles, only the mock insists on behavior verification – the others usually make do with checking state.
A fake repository belongs to the style Fowler calls
classical TDD: real objects wherever possible, and doubles only at the boundaries of the system.
Here the InMemory repository only approximates email uniqueness: it checks it in memory and throws
DuplicateEmailException right away. The final guarantee comes from the unique constraint in the database –
the canonical handler translates its violation into the same exception
(see the race condition in the naive variant).
The test verifies the handler's behavior, not the handling of concurrency, which is why a stub EntityManager is enough.
Test data: a builder instead of a repeated constructor
The tests in the previous examples repeat the same call in every method:
User::register($id, new UserName('Jan Novák'), $email, HashedPassword::fromPlainText('StrongPassword123')). For the test,
one argument matters; the rest is there because the constructor requires it. Once a fifth
parameter appears, all tests change at once.
The solution is the Test Data Builder by Steve Freeman and Nat Pryce from Growing Object-Oriented
Software, Guided by Tests (Addison-Wesley, 2009)
[8]. The builder has a field for each constructor
parameter, initialized to a safe value, chainable methods for overriding these fields,
and a build() method that assembles the target object from them. Optionally, it adds a static factory method
so that the test makes it obvious at first sight what is being built; the authors show it on an OrderBuilder
with an anOrder() method. They sum up the benefit in three points: the builder wraps the syntactic noise around creating
objects, keeps the default case simple and special cases only slightly more complex, and shields tests from changes
to the object's structure – after adding a parameter, a single place changes.
The builder is mutable, so each test calls anOrder() again; an instance shared between tests is
a source of order dependencies that are hard to track down.
An older related pattern is the Object Mother (Peter Schuh, Stephanie Punke, ObjectMother: Easing Test
Object Creation In XP, XP Universe, 2001): a named factory method returns a ready-made fixture,
for example OrderMother::confirmedOrder(). It reads well as long as the variants do not multiply. Fowler criticizes it
for two things [9]: many tests bind to the exact data
of a single fixture, and after the classes change, all mothers have to be migrated at once. The builder relieves this pressure
by letting the caller compose the variant.
In Symfony, fixtures that are meant to end up in the database are handled by zenstruck/foundry[10]. The notation OrderFactory::new()->confirmed()->create()
is the same pattern wrapped in a Doctrine integration. Domain unit tests do not need persistence and make do
with a builder; factories belong in the integration and functional tests of the next two sections.
Integration tests answer a question that unit tests cannot cover: whether the Doctrine mapping, repository
queries, and transactions really do what their interface promises. The default choice is the same
database engine as in production, running in a container. SQLite in-memory is faster, but it differs
in its type system, in the behavior of unique constraints, and in transaction semantics – precisely in what
an integration test is supposed to verify. It remains a deliberate shortcut for fast feedback during local development,
not the configuration CI relies on.
The Doctrine and the InMemory implementations fulfill the same interface contract: findById(UserId $id): ?User
returns null when nothing is found, the same as the InMemory variant from the section on test doubles.
The book keeps both conventions, each for a different case. A command handler that necessarily needs the aggregate
by its identity calls get() and gets a domain exception when it is not found
(OrderNotFoundException::withId() from Domain\Exception). Returning null is left to the find…() methods
where absence is not an error, for example findByEmail() during registration.
The bundle needs two registrations: in config/bundles.php (see Configuration and running)
and in the PHPUnit configuration as a bootstrap extension:
The test container (static::getContainer()) also hands out private services, but only those the compilation
did not remove. A service that no other service uses directly is missing from it, and get() on it fails. A test that
reaches for a concrete implementation therefore makes it public in the test environment:
yamlconfig/services_test.yaml
1services:2# _defaults is not inherited between files. Without it, this definition replaces3# the one from services.yaml entirely, the service is built without arguments, and the tests4# fail with an ArgumentCountError instead of a ServiceNotFoundException.5_defaults:6autowire:true7autoconfigure:true89# Tests only. In production, the service stays private and is reached10# through the injected UserRepository interface.11App\UserManagement\Infrastructure\Repository\DoctrineUserRepository:12public:true
17.06 Functional tests of the API and controllers#
A functional test goes through the whole stack: a request arrives at the controller, passes through the application layer, touches
the database, and returns a response. It checks the HTTP status code, the body (typically JSON), the headers, and the behavior on
erroneous input. In DDD, this is the only test layer that verifies that the presentation and application layers
really work together.
Asynchronous processing through Messenger splits a flow into two halves: dispatching a message and processing it
in a worker. The test has to cover both, each separately. The architecture of the buses is described in the
CQRS chapter, and transactional message handoff in the Outbox Pattern chapter.
In-memory transport
In the test environment, the in-memory:// transport replaces the real broker. Messages go nowhere;
they stay in the process memory and the test picks them up directly from the container. All it takes is overriding the transport
DSN for the test environment:
The examples in this section assume a UserRegistered listener that dispatches the SendWelcomeEmail command on command.bus.
The command is routed by the line App\UserManagement\Application\Command\SendWelcomeEmail: async_commands
added to framework.messenger.routing from the CQRS chapter.
The transport exposes getSent(), getAcknowledged(), and reset(). The cleanup, however, is handled by the framework:
in tests extending KernelTestCase or WebTestCase, all in-memory transports are reset automatically after each
test [13]. The serialize option
(in the DSN in-memory://?serialize=true) also pushes messages through the serialization layer, so the test also covers what travels over the wire in production.
A functional test then verifies that the endpoint really dispatched the message, without waiting for a worker:
zenstruck/messenger-test
Bare assertions over the transport work, but they repeat in every test. The
zenstruck/messenger-test package wraps them in a readable API: the InteractsWithMessenger trait exposes
the transport queue, and the process() method processes the queued messages directly in the test, without starting a worker.
The package brings its own transport and insists on its own DSN. The trait does not work over in-memory://, so the configuration
from the previous example is rewritten to test:// for this style of tests
[14]:
The two configurations are alternatives, not layers: in a given environment, a transport has one DSN. A suite that
stays with in-memory:// makes do with getSent(); a suite built on zenstruck goes to test://
and writes its assertions through the trait.
Testing handler idempotence
An asynchronous transport delivers messages in at-least-once mode: after a worker crash, the same
message can arrive a second time. The handler therefore has to be idempotent: processing it twice may cause only one effect.
The deduplication mechanism is described in Idempotent Inbox, where a record is stored
under the pair eventId (UUID v7) and consumer. The test is short: it calls the handler twice with the same
message and counts the effects.
Testing the outbox
The outbox gives two guarantees, and each needs its own integration test. First: after flush(), the event
sits in the outbox table, written in the same transaction as the aggregate. Second: the relay publishes it
to the transport and marks it as sent (sent). Both variants of the relay process are analyzed in the
Outbox Pattern chapter.
The second test deliberately ends with a pair of assertions: the message went out and the queue of pending records is empty.
If the relay published but did not mark the record as sent, the next run would send the event again.
The rule that the domain layer must not depend on infrastructure or on the application layer holds only until the first
rushed code review in which someone pulls a repository from Infrastructure into an entity. Architecture
tests prevent this technically: the dependency rules are described declaratively, and a violation fails in CI as
a failed test, not only in review.
Deptrac
Deptrac analyzes dependencies statically. The configuration describes layers and the allowed rules
between them (a ruleset); the tool goes through the code and lists the violations. In CI, it runs as a separate step next to
static analysis.
The history of the package matters, because it determines where to look for documentation. The project started
at sensiolabs-de, continued under the QOSSMIC banner, and today has its own organization. The
qossmic/deptrac package is marked as abandoned on Packagist and has been replaced by
deptrac/deptrac[15]. The 4.x series keeps the configuration in the default
deptrac.php file with a typed API; YAML remains supported, but vendor/bin/deptrac init
generates PHP.
In a new project, the rule holds from the first commit. It gets into an existing codebase only through
a baseline: analyse --formatter=baseline writes the current violations to deptrac.baseline.yaml,
the configuration loads it, and the build stays green. New violations then fail, and the old ones are removed gradually.
Without a baseline, the first run ends with a hundred errors and the rule gets thrown out of CI again.
phparkitect as an alternative
Dependency rules can also be enforced by phparkitect (phparkitect/phparkitect)
[16]. It works at a different level than Deptrac: instead of layers,
it describes rules over individual classes, their namespaces, and names, and writes them to a
phparkitect.php file. The tool has its own CLI, does not run through PHPUnit, and in CI runs as a separate
step next to the test suite. Installation and an overview of the rules are in the
Supporting Tactical Patterns chapter; the full configuration for a modular monolith
is shown in the DDD and Microservices chapter.
This section only covers hooking it into the pipeline:
The choice between the two tools is a matter of team preference. Deptrac describes layers and fits broad
rules between them; phparkitect allows finer rules over individual classes (name suffixes,
specific namespaces). Both fail in CI the same way – as a failed build. Projects that use Pest
have a third option: the built-in arch() API writes the same rule as
arch('domain')->expect('App\Domain')->not->toUse('App\Infrastructure') and runs directly inside
the test suite [17].
Code coverage measures what percentage of code lines get executed while the tests run. The metric by itself says nothing
about the quality of the tests: 100% coverage can be reached with tests that only call methods without assertions. It is useful
the other way around, though: where coverage is low, there is code nobody tests, and that is worth a look.
Mutation testing
Coverage tells you which lines a test executed. It does not tell you whether the test would notice if they changed. That question
is answered by mutation testing: the tool introduces small changes into the code (inverts a condition, shifts a boundary, deletes
a call) and runs the tests. A mutation that nobody caught points to a line that has coverage but
no assertion. The share of caught mutations is the mutation score.
In PHP, mutations are generated by Infection [18]. It pays off most over the domain
layer: the logic there is dense, the tests are fast, and the mutations have something to break. On infrastructure, a run takes
a long time and the findings tend to be technical.
Configuration and running
The four test suites from the previous sections are defined in phpunit.dist.xml. PHPUnit looks for its configuration
in the order phpunit.xml, phpunit.dist.xml, phpunit.xml.dist. The older name, phpunit.xml.dist, therefore still works,
only with the lowest priority. The extension for transactional isolation
from the section on integration tests is registered in the same file:
The entry in <extensions> alone is not enough. The dama/doctrine-test-bundle recipe lives in the contrib
repository, so Flex does not run it without confirmation (or without extra.symfony.allow-contrib)
and does not register the bundle. The extension then starts, but it rolls nothing back. The symptom:
the tests pass once and then fail on the second run, on data left over from the first.
The bundle therefore belongs in config/bundles.php:
The test pyramid works in DDD because the domain layer is plain PHP with no dependencies on the framework.
The domain suite can therefore run after every change, not only in CI. Integration and functional tests add
coverage where infrastructure comes in, and architecture tests make sure the isolation of the domain does not disappear
in the next refactoring.
Frequently asked questions
How should an aggregate be tested – a unit test with a mock repository, or an integration test?
An aggregate is tested primarily with a unit test, because it is plain PHP with no dependencies on the framework or the database. The test creates the aggregate, calls its methods, and verifies the resulting state as well as the domain events raised. A mock repository is not needed, because the aggregate itself does not call the repository. An integration test adds coverage only at the level where persistence comes in, that is, when saving and loading the aggregate. A detailed analysis is in the Unit tests of the domain layer section.
What is an InMemory repository for, and when should it be preferred over a mock?
An InMemory repository is a full implementation of the repository interface that keeps aggregates in an in-memory array. Unlike a mock, it simulates real behavior (find, save, count), so tests of application services go through the whole use case more faithfully. A mock fits where a specific interaction matters: how many times a method was called and with which arguments. An InMemory repository, by contrast, serves to verify the outcome, not the calls. The variants are analyzed in the Test doubles and InMemory repositories section.
How do you verify that an aggregate publishes the right domain events?
After the method runs, the list of recorded events is read from the aggregate (typically through releaseEvents()), and the test verifies their type, order, and content. It checks that the aggregate raised exactly the events it should and no extra ones. In a functional test, the same events can be captured through the Messenger event bus to verify how other parts of the system react. A practical example is in the Testing domain events section.
Should the private invariants of an aggregate be tested, or only its public interface?
Only the public interface is tested, that is, the behavior of the aggregate through the methods that the application layer actually calls. Private invariants are an implementation detail. Testing them directly ties the test to a specific code structure and gets in the way of refactoring. A well-designed test verifies that after a series of public calls the aggregate is in a valid state, raised the expected events, and threw a specific domain exception when a rule was violated. A detailed analysis is in the Unit tests of the domain layer section.
What are architecture tests and what do they check?
Architecture tests automatically verify that the code follows the chosen structural rules: for example, that the domain layer does not depend on infrastructure, that aggregates do not call repositories directly, or that controllers do not talk to infrastructure. In PHP, the usual tool for this is Deptrac (the deptrac/deptrac package), which describes the rules declaratively in a deptrac.php file and runs in CI as a separate step next to the test suite. A rule violation shows up as a failed build, not only during code review. The tools and rules are analyzed in the Architecture tests section.