Overview

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 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 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 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 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.
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.
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.

FAQ

Why does hexagonal architecture make testing more mechanical?Because the architecture enforces a stable shape for each artifact type. Commands, handlers, and controllers all have fixed responsibilities and dependency patterns, so the same test recipe can be reused across the codebase instead of inventing a new strategy for every class.
What is the difference between structural verification and behavioral verification?Structural verification checks that the code has the correct architecture shape: packages, annotations, dependency direction, and contracts. Behavioral verification checks what the code actually does at runtime, such as validation results, orchestration, HTTP responses, and adapter mapping.
How should commands and queries be tested?Test them through their validateThenCreate factory. Use valid inputs and assert a right-side result with the expected values, then use invalid inputs and assert a left-side validation error. There are no collaborators or side effects, so this is always the same pattern.
Why are parameterized tests useful for invalid command or query inputs?They let you cover multiple invalid combinations with a single test method. Each scenario becomes one row in a data source, making validation tests concise, readable, and easy to extend without duplicating test logic.
How should handlers be tested in a hexagonal architecture?Mock the output ports, provide a real validated command or query, call handle, and assert the Either result. Then verify the important interactions, such as whether a repository was called once or not called at all when the handler short-circuits.
Why should domain objects not be mocked in handler tests?Because domain objects carry real behavior, such as validation and state transitions. Mocking them removes that behavior from the test and weakens confidence. Handler tests should exercise real domain behavior and focus on orchestration around it.
How are REST controllers tested in this chapter?Mock the command or query bus and the error handler, invoke the controller method with a request DTO, and assert the resulting ResponseEntity. On success, verify the correct HTTP status and body; on failure, verify the bus is skipped and the error handler is used.
What makes adapter testing different from commands, handlers, and controllers?Adapters sit at the boundary with heterogeneous external systems, so they do not all share one fixed recipe. The test strategy depends on what the adapter wraps: mock a repository, use a real in-memory cache, intercept generated client construction, or use MockRestServiceServer for HTTP.
When should you use a real implementation instead of a mock for an adapter?Use the real implementation when the technology is in-process, deterministic, fast, and stateless across tests. In-memory caches are the classic example. If the dependency involves networking, shared state, or timing issues, switch to mocks or dedicated test infrastructure.
What should not be tested in behavioral verification?Do not test getters, framework internals, private methods directly, domain objects through mocks, or integration behavior disguised as unit tests. Also avoid crossing layer boundaries, such as controller tests asserting repository calls. Test only the responsibility of the layer under test.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free