Overview

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 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 “mechanical”?Because the architecture fixes the shape and responsibility of each artifact type. Commands and queries validate themselves, handlers orchestrate ports, controllers dispatch through buses, and adapters wrap specific external systems. Since each type has a stable structure, the same testing recipe can be reused across all classes of that type.
What is the difference between structural verification and behavioral verification?Structural verification checks that classes have the right shape: correct package, annotations, dependencies, and contracts. Behavioral verification checks what the code actually does at runtime: whether invalid input is rejected, the right ports are called, the correct HTTP status is returned, and adapters translate correctly.
How should commands and queries be tested in this architecture?Test them through their validateThenCreate factory. For valid inputs, assert the result is on the right side of Either and that the fields are mapped correctly. For invalid inputs, assert the result is on the left side and contains validation errors. No mocks are needed.
Why are parameterized tests a good fit for invalid command or query inputs?Because invalid cases are naturally a table of scenarios. Each row can represent one bad input combination, such as a null field or empty string. This keeps the test compact while covering the main validation contract without writing many nearly identical tests.
How do you test a handler in hexagonal architecture?Mock the output ports, provide a real validated command or query, call the handler’s handle method, and assert the Either result. Then verify the important interactions, such as a repository call happening once or a save not happening after a failed lookup.
When should a handler test verify interactions instead of only results?When the interaction itself is part of the contract. For example, if a repository lookup fails, the handler must not call save afterward. In those cases, verify call count, call order, or that later ports were never invoked.
How should REST controllers be tested?Mock the command bus or query bus and the error handler, call the controller method with a request DTO, and assert the ResponseEntity status and body. Also verify that the bus is called once on success and that the error handler is used only when needed.
Why are adapters tested differently from commands, handlers, and controllers?Adapters sit at the boundary with the external world, and external systems are heterogeneous. A persistence adapter, cache adapter, OpenAPI client adapter, and HTTP adapter all need different simulation strategies, so there is no single universal recipe for all adapters.
When should you test an adapter with real implementation instead of mocks?Use the real implementation when the technology is in-process, deterministic, fast, and isolated between tests. An in-memory cache is the classic example. In that case, mocking would add little value and may not test meaningful behavior.
What are the main things you should not test in a hexagonal codebase?Do not test compiler-generated getters, framework internals, private methods through reflection, domain objects as mocks, or integration tests disguised as unit tests. Also avoid crossing layer boundaries, such as a handler test asserting repository details or a controller test verifying domain internals.

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