8 Testing the hexagon with behavioral verification
The chapter explains that once hexagonal architecture has been structurally enforced, testing becomes much more predictable: the shape of each artifact is already fixed, so the remaining work is to verify behavior. Structural checks prove the system is built according to the architecture, but behavioral tests prove it actually does the right thing at runtime. This is the key shift in the chapter: from architecture rules that prevent bad designs to unit tests that confirm commands, handlers, controllers, and adapters behave correctly.
For the core application flow, the book presents repeatable recipes. Commands and queries are tested by calling validateThenCreate with valid and invalid inputs and asserting Either results; handlers are tested by mocking output ports, invoking handle, and checking both the returned outcome and the relevant interactions; REST controllers are tested by mocking the bus and error handler, then asserting the HTTP response status, body, and dispatch behavior. The chapter emphasizes BDD-style organization with given, when, and then, along with descriptive @DisplayName text and fluent assertions, so the tests remain readable and consistent across the codebase.
At the boundary with external systems, the testing approach becomes more varied because adapters depend on heterogeneous technologies. Persistence adapters are usually tested by mocking the underlying repository and verifying mapping plus error translation, while lightweight in-memory adapters can be exercised through their real implementation. Generated clients may require construction interception, and HTTP adapters can be tested with server-side request simulation tools. The chapter closes by warning against low-value tests such as getter checks, private-method reflection, mocking domain objects, or writing integration tests disguised as unit tests, arguing that tests should target bugs a developer could realistically introduce and stay focused on each layer’s responsibility.
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