Chapter 8: Testing the hexagon with behavioral verification
The introduction explains why structural checks of WriteFlow’s hexagon must be complemented by behavioral tests.
After this chapter you will be able to
- Structural and behavioral verification. Distinguish what ArchUnit’s structural rules establish from what behavioral tests must verify in WriteFlow. Explain why a class can satisfy the architecture’s rules yet still behave incorrectly.
- Shape and behavior distinction. Distinguish checks that an artifact obeys architectural rules from tests of what it does at runtime in WriteFlow.
- Architecture driven testing regularity. Explain why boundaries, interfaces, dependency inversion, and structural rules make isolated tests repeatable for each core artifact type.
- Core artifact testing patterns. Describe the distinct behavioral checks this section assigns to commands and queries, handlers, and REST controllers.
- Shared test conventions. State the conventions used for WriteFlow tests: given-when-then structure, descriptive DisplayName text, outcome assertions through Either, and verification limited to the layer under test.
- Reusable artifact testing recipes. Explain how to identify recurring artifact types by their responsibilities and dependency patterns, and why their stable shape in hexagonal architecture allows a testing recipe to be reused across classes.
- Three-phase unit test contract. Describe how every WriteFlow test uses given, when, and then to state its precondition, action, and expected outcome, and explain how this makes tests easy to scan.
- Test Names and Report Intent. Distinguish the role of shouldX_whenY method names from @DisplayName, and explain how a descriptive display name helps a team understand a failed test in CI.
- Testing tool roles. Distinguish the roles of JUnit 6, Mockito, and AssertJ, and explain why the same testing approach can use different libraries in another language.
- BDD import vocabulary. Describe how the chosen given and then imports make test setup and assertions read in BDD terms.
- Command and query factory tests. Explain why commands and queries can use the same unit-test pattern, and describe what to assert for valid and invalid inputs to validateThenCreate.
- Valid command creation. Explain what a successful PublishArticleCommand creation test verifies: valid inputs yield Either.right containing a fully constructed command whose components match the inputs.
- Invalid command validation contract. Explain how a parameterized test checks invalid command creation: each row supplies an invalid input combination, and the factory must return an Either.left containing Error.ValidationErrors with at least one validation error.
- Binary construction test pattern. Explain why command and query tests need only successful and unsuccessful construction cases: these objects have no collaborators, side effects, or state transitions.
- Handler orchestration role. Explain that handlers receive a validated command or query, coordinate output ports and repositories, and return an Either<Error, R> while delegating business logic to domain objects.
- Repeatable handler test recipe. Describe how to configure mocked or in-memory output ports for success or failure, call handle, and assert the Either result. Explain when verifying port calls adds value beyond checking observable results or state.
- Handler test dependency wiring. Explain how MockitoExtension supports a handler test and how Mockito supplies the handler’s constructor dependencies. Describe why the test stubs only the getters the handler calls.
- Handler happy-path verification. Explain what the handler’s success test covers and why it uses a real domain object rather than a mock. Distinguish verification of handler orchestration from testing the repository.
- Handler not-found behavior. Explain that when the repository returns an empty Optional, the handler must return an ArticleNotFound error without calling save, and that the test verifies the absent save call with never().
- Handler test scaffold and sequence. Describe the common handler-test scaffold and the order of a test: stub command fields, configure port responses, call handle, assert the Either result, and verify interactions. Explain that handlers differ in their ports and orchestration steps.
- Controller boundary responsibility. Explain how a REST controller receives an HTTP request, constructs and dispatches a command or query through a bus, and translates the Either result into an HTTP response rather than owning business logic.
- Repeatable controller test recipe. Describe the controller test recipe: mock the appropriate bus and error handler, configure a right or left bus result, call the controller, then assert the ResponseEntity and verify the relevant interactions. Explain what remains the same across endpoints and what changes.
- Controller test scaffold components. Describe the ArticleController test scaffold: controllers dispatch commands and queries through their respective buses, both buses are mocked, and ApiErrorHandler maps domain errors to HTTP ProblemDetail responses.
- Controller happy-path verification. Describe how the test sends a directly instantiated request DTO to the controller and checks that the response is successful, the bus is called exactly once, and the error handler is not called.
- Validation Failure Without Dispatch. Explain that when command validation fails, the controller maps the validation error to a response without dispatching the command, and the test verifies that the bus is not called.
- Bus Failure Delegation. Explain that when the bus returns Either.left, the controller passes that result through without determining where the failure occurred; the controller test verifies delegation, while error-handler tests verify response mapping.
- Query endpoint success contract. Explain how to test a successful query endpoint when the query bus returns a domain DTO in Either.right: check the response status and body type, and verify that the bus was called once.
- Controller test decision tree. Explain how the controller test scaffold covers both possible outcomes: successful dispatch through a bus and bus failure delegated to the error handler.
- Adapter testing heterogeneity. Explain why adapters do not share the fixed testing recipe used for commands, handlers, and controllers, and state the rule for choosing an adapter test strategy.
- Persistence adapter test boundary. Explain how a persistence adapter translates between domain entities and persistence models, and describe how to test that translation without using a real database.
- Real Implementation Test Criteria. Explain why an in-memory cache adapter can be tested with its real implementation instead of mocks, and state when that choice should change.
- Generated client construction mocking. Explain why testing an adapter that constructs a generated OpenAPI client requires Mockito's mockConstruction, and why the adapter must be instantiated manually inside its active try block rather than with @InjectMocks.
- HTTP Adapter Interaction Testing. Explain how MockRestServiceServer tests an adapter that uses Spring's RestClient directly, including how it intercepts requests and verifies the adapter's interactions.
- Dependency-driven adapter test selection. Explain why adapter tests use different sub-patterns and describe how to choose a simulation strategy from the adapter's dependency.
- Layer Responsibility Boundaries. Explain why tests should verify each layer's own responsibility rather than the behavior of adjacent layers. Describe how crossing those boundaries makes tests fragile and failures misleading.
- Real Domain Behavior. Explain why domain entities, value objects, and aggregates should be real objects rather than mocks in these tests, even when a data-carrying command is mocked.
- Framework Test Boundaries. Distinguish pure unit tests from integration tests that require a database, server, or Spring context, and explain when framework-dependent behavior warrants a focused integration test rather than a test of framework internals or annotations alone.
What it builds on
- Executing the rules: The test suite (chapter 7) · The execution of ArchUnit rules that check WriteFlow’s structural form.
- Dependency rules: Who may import whom (chapter 7) · Dependency rules are one kind of structural constraint already established.
- Structural rules: Shape enforcement (chapter 7) · Structural rules establish consistent artifact shapes.
- Commands and queries as typed input (chapter 4) · Commands and queries are typed inputs.
- From use case interface to handler implementation (chapter 4) · Handlers implement use cases.
- Input adapters: Driving the hexagon (chapter 5) · Controllers are input adapters.
- Either: An honest signature (chapter 4) · The architecture uses Either to represent error-handling outcomes.
- The recommended approach: validateThenCreate (chapter 3) · The validateThenCreate factory approach.
Section by section
Introduction
The introduction explains why structural checks of WriteFlow’s hexagon must be complemented by behavioral tests.
- Structural and behavioral verification: Distinguish what ArchUnit’s structural rules establish from what behavioral tests must verify in WriteFlow. Explain why a class can satisfy the architecture’s rules yet still behave incorrectly.
Why it matters: Passing architecture checks does not mean WriteFlow returns the right results or rejects bad input.
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.
- Shape and behavior distinction: Distinguish checks that an artifact obeys architectural rules from tests of what it does at runtime in WriteFlow.
Why it matters: Passing structural checks does not show that a command rejects bad input or a controller returns the right response. - Architecture driven testing regularity: Explain why boundaries, interfaces, dependency inversion, and structural rules make isolated tests repeatable for each core artifact type.
Why it matters: The investment in architectural boundaries pays off in predictable tests rather than a new testing strategy for every class. - Core artifact testing patterns: Describe the distinct behavioral checks this section assigns to commands and queries, handlers, and REST controllers.
Why it matters: These checks tie each test to the responsibility of the artifact being tested. - External adapter testing variation: Explain why a single universal testing recipe does not extend to adapters that communicate with external systems.
Why it matters: It prevents the reader from forcing one core-artifact recipe onto every kind of external integration.
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.
- Shared test conventions: State the conventions used for WriteFlow tests: given-when-then structure, descriptive DisplayName text, outcome assertions through Either, and verification limited to the layer under test.
Why it matters: These conventions give readers a consistent way to interpret the tests that follow. - Reusable artifact testing recipes: Explain how to identify recurring artifact types by their responsibilities and dependency patterns, and why their stable shape in hexagonal architecture allows a testing recipe to be reused across classes.
Why it matters: Recognizing recurring artifact types helps readers apply a fitting recipe to more than one class.
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.
- Three-phase unit test contract: Describe how every WriteFlow test uses given, when, and then to state its precondition, action, and expected outcome, and explain how this makes tests easy to scan.
Why it matters: The shared structure makes a test’s action and definition of success quick to find. - JUnit and Cucumber distinction: Distinguish WriteFlow’s use of BDD labels in ordinary JUnit unit tests from Cucumber’s executable, plain-text scenarios.
Why it matters: Using BDD’s structure does not require adopting Cucumber or testing the whole application.
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.
- Test Names and Report Intent: Distinguish the role of shouldX_whenY method names from @DisplayName, and explain how a descriptive display name helps a team understand a failed test in CI.
Why it matters: A clear CI failure report tells the team which behavior broke, especially during refactors or dependency upgrades.
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.
- Testing tool roles: Distinguish the roles of JUnit 6, Mockito, and AssertJ, and explain why the same testing approach can use different libraries in another language.
Why it matters: Separating the roles helps you understand the tests without depending on these particular Java libraries. - Either in test assertions: Explain why Vavr appears among the testing tools even though it is not a test dependency.
Why it matters: This distinction explains why a production error-handling type is part of the tests' vocabulary. - BDD import vocabulary: Describe how the chosen given and then imports make test setup and assertions read in BDD terms.
Why it matters: Consistent names make it easier to see where a test sets up collaborators and where it checks the result.
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.
- Command and query factory tests: Explain why commands and queries can use the same unit-test pattern, and describe what to assert for valid and invalid inputs to validateThenCreate.
Why it matters: The same two-path test checks every command and query without setting up collaborators.
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.
- Valid command creation: Explain what a successful PublishArticleCommand creation test verifies: valid inputs yield Either.right containing a fully constructed command whose components match the inputs.
Why it matters: This test can catch a command that is created successfully but contains values in the wrong components. - Creation test structure: Describe the test structure shown for valid command creation, including why its given section needs no setup in this example.
Why it matters: It keeps this command-creation test focused on the factory result rather than unrelated collaborators.
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.
- Invalid command validation contract: Explain how a parameterized test checks invalid command creation: each row supplies an invalid input combination, and the factory must return an Either.left containing Error.ValidationErrors with at least one validation error.
Why it matters: It verifies rejection of invalid commands without making every test depend on exact error wording. - Parameterized test setup placement: Describe when a parameterized validation test can omit a separate // given section and when it should include one.
Why it matters: It keeps the test readable without hiding setup the test actually needs.
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.
- Binary construction test pattern: Explain why command and query tests need only successful and unsuccessful construction cases: these objects have no collaborators, side effects, or state transitions.
Why it matters: This keeps tests focused on the behavior these objects actually have. - Always-valid entity test reuse: Describe how the same construction-test structure applies to domain entities built with validateThenCreate, with differences in their fields and invalid combinations.
Why it matters: The same test structure can cover more than commands and queries. - Focused invalid input selection: State which invalidInputs() cases to prioritize and why this avoids an unnecessarily large combination matrix.
Why it matters: A small, deliberate input set can cover common validation cases without multiplying tests needlessly.
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.
- Handler orchestration role: Explain that handlers receive a validated command or query, coordinate output ports and repositories, and return an Either<Error, R> while delegating business logic to domain objects.
Why it matters: The handler’s limited role tells you what a handler test needs to exercise. - Repeatable handler test recipe: Describe how to configure mocked or in-memory output ports for success or failure, call handle, and assert the Either result. Explain when verifying port calls adds value beyond checking observable results or state.
Why it matters: The same recipe can test different handlers without making every collaborator call an assertion. - Validated test input choice: Distinguish when to pass a real command or query and when to mock one in a handler test, while keeping command validation in its own tests.
Why it matters: Valid, straightforward input keeps the test focused on what the handler does.
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.
- Handler test dependency wiring: Explain how MockitoExtension supports a handler test and how Mockito supplies the handler’s constructor dependencies. Describe why the test stubs only the getters the handler calls.
Why it matters: This wiring is the repeatable starting point for the handler tests that follow. - Publish handler behavior paths: Trace the PublishArticleHandler’s success path and state the two failure conditions identified for testing.
Why it matters: These paths define the behavior the subsequent handler tests need to check.
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.
- Handler happy-path verification: Explain what the handler’s success test covers and why it uses a real domain object rather than a mock. Distinguish verification of handler orchestration from testing the repository.
Why it matters: The test can verify the handler’s behavior without replacing its domain collaboration with a mock or mistaking it for a repository test.
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.
- Handler not-found behavior: Explain that when the repository returns an empty Optional, the handler must return an ArticleNotFound error without calling save, and that the test verifies the absent save call with never().
Why it matters: The test catches a handler that reports the right error but still attempts to persist a nonexistent article.
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.
- Handler test scaffold and sequence: Describe the common handler-test scaffold and the order of a test: stub command fields, configure port responses, call handle, assert the Either result, and verify interactions. Explain that handlers differ in their ports and orchestration steps.
Why it matters: The fixed pattern makes it easier to test each handler’s particular behavior without redesigning the test structure. - Value of test regularity: Explain why structurally similar handler tests scale across a project: a teammate can follow an existing example and concentrate on the handler’s business behavior.
Why it matters: A familiar test shape helps a team add handler tests without repeatedly deciding how to organize them.
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.
- Controller boundary responsibility: Explain how a REST controller receives an HTTP request, constructs and dispatches a command or query through a bus, and translates the Either result into an HTTP response rather than owning business logic.
Why it matters: This boundary tells you what a controller test should verify without testing business logic in the controller. - Repeatable controller test recipe: Describe the controller test recipe: mock the appropriate bus and error handler, configure a right or left bus result, call the controller, then assert the ResponseEntity and verify the relevant interactions. Explain what remains the same across endpoints and what changes.
Why it matters: The shared recipe makes controller behavior testable in the same way across WriteFlow endpoints.
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.
- Controller test scaffold components: Describe the ArticleController test scaffold: controllers dispatch commands and queries through their respective buses, both buses are mocked, and ApiErrorHandler maps domain errors to HTTP ProblemDetail responses.
Why it matters: This scaffold provides a consistent starting point for controller tests.
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.
- Controller happy-path verification: Describe how the test sends a directly instantiated request DTO to the controller and checks that the response is successful, the bus is called exactly once, and the error handler is not called.
Why it matters: These checks show that a successful request follows the intended controller path without accidentally invoking error handling.
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.
- Validation Failure Without Dispatch: Explain that when command validation fails, the controller maps the validation error to a response without dispatching the command, and the test verifies that the bus is not called.
Why it matters: The test checks that invalid input stops at the controller boundary. - Bus Failure Delegation: Explain that when the bus returns Either.left, the controller passes that result through without determining where the failure occurred; the controller test verifies delegation, while error-handler tests verify response mapping.
Why it matters: Separating delegation from error mapping keeps the controller test focused on its own responsibility.
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.
- Query endpoint success contract: Explain how to test a successful query endpoint when the query bus returns a domain DTO in Either.right: check the response status and body type, and verify that the bus was called once.
Why it matters: These assertions check the endpoint’s essential behavior without requiring every DTO field to be tested.
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.
- Controller test decision tree: Explain how the controller test scaffold covers both possible outcomes: successful dispatch through a bus and bus failure delegated to the error handler.
Why it matters: These two cases give you a clear boundary for controller test coverage. - Reusable endpoint test structure: Describe what stays the same when adding endpoint tests and which details change.
Why it matters: A stable test structure makes it easier to add endpoint coverage consistently.
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.
- Adapter testing heterogeneity: Explain why adapters do not share the fixed testing recipe used for commands, handlers, and controllers, and state the rule for choosing an adapter test strategy.
Why it matters: This gives you a consistent way to choose tests without forcing every adapter into one recipe. - Dependency matched test sub-patterns: Describe the testing sub-patterns given for repository-facing adapters, lightweight in-process technology, and generated or internally constructed clients.
Why it matters: These examples show how the dependency-first rule leads to concrete test choices.
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.
- Persistence adapter test boundary: Explain how a persistence adapter translates between domain entities and persistence models, and describe how to test that translation without using a real database.
Why it matters: It keeps the test focused on the adapter’s responsibility rather than the database technology. - Persistence test path coverage: Describe the typical success, read not-found, and infrastructure-failure paths in persistence adapter tests, including what write-operation tests verify.
Why it matters: The paths give a repeatable test structure without overlooking entity-specific mapping checks.
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.
- Real Implementation Test Criteria: Explain why an in-memory cache adapter can be tested with its real implementation instead of mocks, and state when that choice should change.
Why it matters: The right test setup exercises meaningful adapter behavior without introducing slow or unreliable dependencies. - Cache Test Isolation and Observation: Describe how the adapter test stays isolated and observes cache state without Mockito mocks.
Why it matters: Fresh state and direct observation let the test check the real adapter without mock-interaction assertions.
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.
- Generated client construction mocking: Explain why testing an adapter that constructs a generated OpenAPI client requires Mockito's mockConstruction, and why the adapter must be instantiated manually inside its active try block rather than with @InjectMocks.
Why it matters: The test can control the generated client only if interception is active when the adapter creates it.
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.
- HTTP Adapter Interaction Testing: Explain how MockRestServiceServer tests an adapter that uses Spring's RestClient directly, including how it intercepts requests and verifies the adapter's interactions.
Why it matters: The test can check what the adapter actually sends without making a network call. - HTTP Failure Boundary: Explain what the adapter must do with HTTP failures before they reach the hexagon.
Why it matters: A transport failure should be expressed in the application's own error language at the boundary.
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.
- Dependency-driven adapter test selection: Explain why adapter tests use different sub-patterns and describe how to choose a simulation strategy from the adapter's dependency.
Why it matters: Choosing the test setup from the dependency makes adapter tests fit the technology they exercise. - Shared adapter test structure: Describe what remains consistent across adapter tests even when their dependency simulation differs.
Why it matters: Different test setups do not change what the tests must verify.
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.
- Layer Responsibility Boundaries: Explain why tests should verify each layer's own responsibility rather than the behavior of adjacent layers. Describe how crossing those boundaries makes tests fragile and failures misleading.
Why it matters: Keeping tests at the right boundary makes failures more useful and the suite easier to maintain. - Real Domain Behavior: Explain why domain entities, value objects, and aggregates should be real objects rather than mocks in these tests, even when a data-carrying command is mocked.
Why it matters: Using real domain objects lets a test encounter the business behavior it claims to exercise. - Low Value Test Targets: Describe why separate tests of generated accessors, private methods through reflection, and domain-construction details inside handler tests add little confidence or test the wrong concern.
Why it matters: Asking what plausible bug a test catches helps keep the suite useful instead of merely large. - Framework Test Boundaries: Distinguish pure unit tests from integration tests that require a database, server, or Spring context, and explain when framework-dependent behavior warrants a focused integration test rather than a test of framework internals or annotations alone.
Why it matters: Choosing the right test level avoids paying integration-test costs without gaining confidence in real framework behavior.
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
- Behavioral tests: Applying the chapter 8 recipes (chapter 9) · Motivates behavioral tests alongside the architecture checks used to verify WriteFlow.
Concepts explained in this chapter
- unit testA testing technique that verifies small units of software in isolation from their dependencies.
- commandA command object encapsulates data representing a requested application operation.
- entityA domain object with an identity whose state and invariants are governed by domain rules.
- integration testA test that verifies interactions between multiple application components or an application and an external system.
- queryA query is a request that retrieves information without changing application or domain state.
- adapterAn adapter that connects an application to an external service through an API.
- handlerA handler is an application component that processes a request and coordinates the interactions needed to fulfill it.
- REST controllerAn adapter that accepts REST requests and translates them into calls to application input ports.
- persistence adapterAn adapter that implements persistence contracts and translates between domain objects and storage technology.
- command and query busAn application component that accepts commands through a uniform interface and dispatches them to corresponding handlers.
- driving adapterA primary adapter translates an external trigger into a call to an application input port.
- factoryA construction abstraction that creates objects while encapsulating their creation logic.
- EitherEither is a functional data type representing one of two alternatives, commonly a failure value or a successful result.
- transaction boundaryA transaction boundary defines the scope within which a set of operations participates in one atomic transaction.
- outbound portAn application-facing boundary that declares a service the application requires from an external system.
- validatethencreateA construction pattern that validates all required constraints before creating an object and returns validation errors instead of an invalid object.
- data mappingData mapping is the transformation of data between representations used by different system components or layers.
- orchestrationThe coordination of collaborators to complete an application operation without owning the underlying business rules.
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.
