liveBook · Manning

Chapter 8: Testing the hexagon with behavioral verification

What you will learn in chapter 8 of Clean Applications with Hexagonal Architecture

The introduction explains why structural checks of WriteFlow’s hexagon must be complemented by behavioral tests.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction explains why structural checks of WriteFlow’s hexagon must be complemented by behavioral tests.

Key terms: structural verification, behavioral verification, ArchUnit rules, validateThenCreate

8.1 From shape to behavior

This section distinguishes structural correctness from runtime behavior and explains why hexagonal architecture makes behavioral tests repeatable for core artifacts but less uniform for external adapters.

Key terms: shape, behavior, structural correctness, dependency inversion, test doubles, structural rules, testing recipe, validateThenCreate, Either<Error, T>, output ports

8.2 The testing recipe

This section establishes shared conventions for readable, consistent tests and explains why recurring hexagonal artifact types make testing recipes reusable.

Key terms: given-when-then, DisplayName, Either, layer under test, artifact type, responsibility, dependency pattern, testing recipe

8.2.1 The BDD contract

This section establishes a three-phase BDD structure for WriteFlow’s unit tests and explains why it uses that structure in JUnit rather than Cucumber.

Key terms: BDD, given, when, then, inline comments, JUnit, Cucumber, Gherkin, unit tests

8.2.2 Naming intent with @DisplayName

This section explains how @DisplayName makes a test’s intended behavior clear in CI reports while method names remain useful for navigating code.

Key terms: shouldX_whenY, @DisplayName, CI

8.2.3 The tooling foundation

This section identifies the tools used in the Java tests, distinguishes their roles, and establishes consistent BDD-style test vocabulary.

Key terms: JUnit 6, Mockito, AssertJ, test doubles, Vavr, compile dependency, Either<Error, T>, BDDMockito.given, BDDAssertions.then, given–when–then

8.3 Commands and queries: Always the same test

This section gives a repeatable unit-test recipe for commands and queries: check that their factory accepts valid input and reports invalid input.

Key terms: commands, queries, validateThenCreate, Either<Error, T>, right side, left side

8.3.1 Testing valid command creation

Shows how to test that valid inputs produce a correctly constructed command without mocks or setup.

Key terms: PublishArticleCommand, validateThenCreate, Either.right, record's components, @Test, // given, constants

8.3.2 Testing the validation path

This section shows how to test that command factories reject invalid inputs and return validation errors.

Key terms: factory method, Either.left, Error.ValidationErrors, parameterized tests, // given, @MethodSource, test parameters, shared setup

8.3.3 The universal pattern

This subsection reduces command and query tests to construction success or failure, extends the pattern to always-valid domain entities, and suggests a focused set of invalid inputs.

Key terms: commands, queries, construct successfully, validateThenCreate, Always-Valid Model, invalidInputs(), validation contract

8.4 Handlers: Mock ports, verify interactions

This section explains why handlers can be tested with a repeatable recipe that controls their collaborators and checks observable behavior.

Key terms: handler, output ports, repositories, Either<Error, R>, in-memory fakes, Either.right, Either.left, handle, command, query

8.4.1 The handler test scaffold

This section identifies the PublishArticleHandler behavior to test and explains the common Mockito wiring for handler tests.

Key terms: MockitoExtension, JUnit 6, constructor, stub, PublishArticleHandler, PublishArticleCommand, repository, domain method

8.4.2 Testing the happy path

This subsection defines the handler happy-path test and explains why it should exercise a real domain object while verifying orchestration rather than the repository.

Key terms: handler, domain model, mock domain object, orchestrates

8.4.3 Testing the not-found path

This subsection shows how to test a handler when the requested article does not exist.

Key terms: empty Optional, ArticleNotFound, never(), save

8.4.4 Testing the persistence failure path

8.4.5 The universal pattern

This section gives a repeatable handler-test pattern and explains why its consistency helps teams focus on behavior.

Key terms: @Mock ports, @Mock command, @InjectMocks handler, handle, Either, verify interactions, mechanical regularity, structural decisions, business behavior

8.5 REST controllers: The input adapter recipe

This section explains the shared role of REST controllers as input adapters and a repeatable way to test their HTTP responses and interactions.

Key terms: REST controllers, input adapters, command or query, bus, Either, command bus, query bus, error handler, right or left, ResponseEntity

8.5.1 The controller test scaffold

This subsection identifies the reusable test scaffold for controllers that dispatch through command and query buses.

Key terms: ArticleController, command bus, query bus, ApiErrorHandler, ProblemDetail

8.5.2 Testing the happy path

This subsection shows how to test a controller’s successful request path by checking its response and interactions with the bus and error handler.

Key terms: request DTO, status codes, InOrder verification, verifyNoInteractions, errorHandler

8.5.3 Testing the bus failure path

This subsection shows how controller tests verify two failure paths: invalid commands are not dispatched, and bus failures are delegated without interpretation.

Key terms: command validation, bus, Either.left, error handler, delegation

8.5.4 Testing a query endpoint

This section identifies the essential assertions for testing a successful query endpoint.

Key terms: query endpoint, query bus, domain DTOs, Either.right

8.5.5 The universal pattern

This section gives a repeatable controller-test pattern based on the controller’s two possible outcomes: successful dispatch or an error delegated to the error handler.

Key terms: @Mock buses, @Mock error handler, @InjectMocks controller, bus failure, command/query type, request DTO, expected HTTP status

8.6 Adapters with external dependencies

Adapter tests need different strategies because adapters wrap different kinds of external dependencies; the dependency determines the testing sub-pattern.

Key terms: heterogeneity principle, external dependency, sub-pattern, repository interface, mapping, error translation, in-memory cache, generated or internally constructed client

8.6.1 Persistence adapters: Mocking the infrastructure layer

This section explains how to test persistence adapters by mocking database access while checking mapping, delegation, and failure paths.

Key terms: persistence adapter, repository output port, domain entities, persistence model, data repository interface, success, not-found, infrastructure failure, Spring Data, DataAccessException

8.6.2 Technology-specific adapters: Testing with real implementations

This subsection explains when to test a technology-specific adapter with a real implementation and how to keep that test isolated.

Key terms: real implementation, in-memory caches, mocks, dedicated test infrastructure, @BeforeEach, get method, system under test

8.6.3 External API adapters: Mocking construction

This section explains how to mock a generated OpenAPI client that an adapter creates in its constructor.

Key terms: OpenAPI specification, ApiClient, mockConstruction, @InjectMocks

8.6.4 HTTP adapters: MockRestServiceServer

This section shows how to test a RestClient-based HTTP adapter’s requests and keep HTTP failures out of the hexagon.

Key terms: RestClient, RestClient.Builder, MockRestServiceServer, server.verify(), domain error model, HTTP status codes, hexagon

8.6.5 The heterogeneity principle

Adapter tests share a BDD and Either-based structure, but the way they simulate an external dependency depends on what that dependency is.

Key terms: heterogeneity principle, sub-pattern, Data interface, MockRestServiceServer, mockConstruction, BDD structure, Either results

8.7 What not to test

This section explains how to avoid low-value tests by testing each hexagonal layer at the right level of abstraction and choosing tests that catch plausible bugs.

Key terms: level of abstraction, commands, handlers, adapters, controllers, domain entities, value objects, aggregates, domain logic, command

8.8 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 7: Enforcing the architecture as executable specification Chapter 9: Building WriteFlow: The complete implementation →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.