chapter eight

8 Testing the hexagon with behavioral verification

 

This chapter covers

  • Understanding why hexagonal architecture makes testing mechanical
  • Unit testing commands and queries through the validateThenCreate contract
  • Unit testing handlers by mocking output ports
  • Unit testing REST controllers by mocking the bus
  • Unit testing adapters that interface with heterogeneous external systems
  • Recognizing what not to test

We proved that WriteFlow's hexagon has the structural form. ArchUnit rules enforce dependency direction, annotation placement, structural contracts, and naming conventions. If a class violates the architecture, the build fails before anyone writes a test for it.

Shape is necessary but not sufficient. A handler that satisfies every structural rule—correct annotations, package, and generic signature—can still return the wrong result. A command that passes ArchUnit's validateThenCreate shape check can still accept invalid input. A controller that lives in the right adapter package can still return the wrong HTTP status. Structural verification proves the hexagon looks correct. Behavioral verification proves it works correctly.

8.1 From shape to behavior

8.2 The testing recipe

8.2.1 The BDD contract

8.2.2 Naming intent with @DisplayName

8.2.3 The tooling foundation

8.3 Commands and queries: Always the same test

8.3.1 Testing valid command creation

8.3.2 Testing the validation path

8.3.3 The universal pattern

8.4 Handlers: Mock ports, verify interactions

8.4.1 The handler test scaffold

8.4.2 Testing the happy path

8.4.3 Testing the not-found path

8.4.4 Testing the persistence failure path

8.4.5 The universal pattern

8.5 REST controllers: The input adapter recipe

8.5.1 The controller test scaffold

8.5.2 Testing the happy path

8.5.3 Testing the bus failure path

8.5.4 Testing a query endpoint

8.5.5 The universal pattern

8.6 Adapters with external dependencies

8.6.1 Persistence adapters: Mocking the infrastructure layer

8.6.2 Technology-specific adapters: Testing with real implementations

8.6.3 External API adapters: Mocking construction

8.6.4 HTTP adapters: MockRestServiceServer

8.6.5 The heterogeneity principle

8.7 What not to test

8.8 Summary