8 Testing the hexagon with behavioral verification
This chapter explains how hexagonal architecture turns testing from an open-ended design problem into a set of repeatable behavioral checks. Once structural rules guarantee that the code has the right shape, the focus shifts to proving that each artifact actually behaves correctly at runtime. The central idea is that the architecture itself makes unit testing mechanical: commands and queries, handlers, and controllers all follow stable patterns, so developers can apply the same recipe every time instead of improvising a new strategy for each class.
The core testing recipe is based on BDD-style tests with a clear given-when-then flow, readable display names, and assertions expressed with fluent APIs. Commands and queries are tested by calling their validation factory with valid and invalid inputs and checking the right or left side of an Either result. Handlers are tested by mocking output ports, invoking the handle method, and verifying both the returned result and the essential interactions. REST controllers are tested by mocking the bus and error handler, then asserting that requests are dispatched correctly and mapped to the expected HTTP response. These patterns are intentionally uniform, which makes test suites predictable and easy to maintain.
At the adapter boundary, however, the chapter emphasizes that testing becomes more varied because external systems are heterogeneous. Persistence adapters are usually tested by mocking the underlying repository and verifying mappings and error translation, lightweight in-memory adapters can often be tested with their real implementation, and HTTP or generated-client adapters may require specialized tools to intercept construction or simulate network calls. The chapter closes by warning against wasted effort: do not test getters, private methods, framework internals, or interactions that belong to another layer. Each test should target the responsibility of its own layer and catch a plausible bug, while leaving the neighboring layers to their own tests.
The testing matrix: artifact type determines the recipe. The mechanical zone (commands, handlers, controllers) uses one fixed recipe per type. The heterogeneous zone (adapters) branches by external technology.
The BDD test contract used throughout WriteFlow. Every unit test follows the same three-phase structure: given establishes preconditions, when performs exactly one action, and then asserts outcomes.
The command/query testing recipe. Inputs flow into validateThenCreate and produce one of two outcomes: a valid instance on the right side or validation errors on the left side.
The handler testing recipe. A mocked command and mocked output ports drive the handler, while real domain behavior remains inside the orchestration path and errors short-circuit later steps.
The controller testing recipe. The controller receives an HTTP request, dispatches through the bus, and either returns a success response or delegates error translation to the API error handler.
Choosing an adapter testing strategy. Unlike the mechanical core of the hexagon, adapters are tested with different sub-patterns depending on the kind of external dependency they wrap.
Summary
- Hexagonal architecture makes unit testing mechanical. Each artifact type—command, handler, controller—follows an identical recipe that never varies across instances.
- The BDD contract (// given, // when, // then) combined with @DisplayName turns every test into a readable specification. BDDMockito.given() for setup, BDDAssertions.then() for verification.
- Commands and queries are tested by calling validateThenCreate with valid inputs (assert right side, verify fields) and invalid inputs (assert left side, verify ValidationErrors). No mocks, no setup—pure input/output.
- Handlers are tested by mocking the command and the output ports, calling handle, asserting the Either result, and verifying interactions. The scaffold—@Mock ports + @Mock command + @InjectMocks handler—is identical for every handler in the system.
- REST controllers are tested by mocking the bus and the error handler, calling the controller method, and asserting the ResponseEntity status and body. Two paths cover the entire decision tree: bus succeeds, or bus fails.
- Adapters are the one place where tests vary—because external systems are heterogeneous. Sub-patterns emerge: mock Spring Data for persistence, use real implementations for in-memory caches, use mockConstruction for OpenAPI clients, use MockRestServiceServer for RestClient adapters.
- Knowing what not to test is as important as knowing what to test. Do not test getters, framework internals, private methods, or domain state inside handler tests. Each layer tests its own responsibility.
- The architecture's return on investment is predictability. A new team member does not decide how to test a handler—the recipe is identical for every handler. A project with fifty handlers has fifty test classes that are structurally indistinguishable.
Clean Applications with Hexagonal Architecture ebook for free