A class can satisfy every architectural rule and still return the wrong result. A unit test verifies behavior of a small software unit in isolation from its dependencies. Structural rules check boundaries and signatures; unit tests check what the component actually does. section 8.0 section 8.1
Hexagonal architecture makes isolation repeatable: commands and queries have no collaborators, while handlers depend on output-port interfaces that can be replaced with mocks. Each artifact type has a testing recipe tied to its responsibility. section 8.1
Choose assertions for the unit’s job:
- Commands and queries: call validateThenCreate with valid inputs and check the populated right result; use invalid inputs to check the left result and validation errors. No mocks are needed. section 8.3
- Handlers: mock the command and output ports, call handle, then assert the Either result and verify port interactions. Test orchestration rather than domain construction. section 8.8 section 8.7
- REST controllers: mock the bus and error handler, call the controller method, and assert the ResponseEntity status and body for success and failure. section 8.8
- Adapters: choose a strategy for the external technology, such as mocking Spring Data, using a real in-memory cache, or using MockRestServiceServer for a RestClient adapter. section 8.8
Figure 8.1 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 separates fixed recipes for core artifacts and controllers from technology-specific adapter strategies. section 8.1
A command creation test
In a JUnit test, given a valid identifier, call its validateThenCreate factory once, then assert that the result is right and contains the supplied value. A separate invalid-input test checks the left result and meaningful validation errors. Label the phases given, when, and then so the behavior is easy to scan. section 8.2.1 section 8.3
Keep tests at the right abstraction level. Do not test getters, framework internals, or private methods directly; complex private logic may be a signal to extract a collaborator. Avoid checking domain-object state in a handler test when domain tests already own construction. A test requiring a running database, HTTP server, or Spring application context is an integration test, not an isolated unit test. Prefer tests that would catch a plausible mistake. section 8.7 section 8.8

















