Testing the core with in-memory adapters
Author ultra-fast, deterministic unit tests for hexagonal use cases and domain models by substituting driven ports with in-memory fake adapters.
Contentsand lesson path
On this page
- The Testing Dilemma: Mocks vs. Fakes in Hexagonal Design
- Authoring Stateful In-Memory Adapters
- Hands-On Lab: Verifying Domain Invariants with Fakes
- Closing the Contract Gap: Shared Contract Suites
Lessons of Clean & Hexagonal Architecture
- Which way dependencies point: layers, the MVC family, ports and adapters Concept · 25 min
- Driving ports, driven ports and the composition root Concept · 20 min
- Moving a layered service to hexagonal Lab · 30 min
- Testing the core with in-memory adapters Lab · 20 min
- When a plain layered design is the better choice Concept · 10 min
- Dependency rule check Knowledge check · 6 questions
What you will learn
- Test domain and application logic without a database or network by substituting adapters.
Prerequisites: Software Design Principles
01. The Testing Dilemma: Mocks vs. Fakes in Hexagonal Design
In traditional layered systems, unit testing application logic is notoriously painful. When a service directly imports database connection pools, ORM sessions, and external HTTP clients, developers are forced to choose between two unpalatable testing strategies:
- Slow Integration Tests: Spin up real Docker containers running PostgreSQL, Redis, and mock SMTP servers for every test suite. While realistic, these test suites take minutes to execute, suffer from transient network timeouts, and quickly decay into flaky tests that developers ignore.
- Brittle Mocking Frameworks: Use dynamic mocking libraries to patch individual database methods (e.g.,
mock_session.query().filter().first()). This couples test assertions directly to the internal implementation mechanics of the query rather than the observable business behavior. When an engineer refactors a SQL query to use a join instead of a subselect, fifty unit tests break despite business behavior remaining identical.
Hexagonal Architecture offers a superior third way: In-Memory Fake Adapters. Because the core depends strictly on abstract driven ports, test suites substitute production infrastructure with lightweight, stateful, in-memory implementations.
03. Hands-On Lab: Verifying Domain Invariants with Fakes
Review the complete, self-contained Python test script below. It sets up an InMemoryInvoiceRepository and InMemoryNotificationAdapter, injects them into SettleInvoiceService, and rigorously tests both the happy path and critical domain failure invariants in milliseconds.
from dataclasses import dataclass
from typing import Protocol, List, Optional, Dict
from datetime import datetime
@dataclass
class InvoiceLine:
description: str
quantity: int
unit_price: float
@property
def total(self) -> float:
return round(self.quantity * self.unit_price, 2)
@dataclass
class Invoice:
invoice_id: str
customer_id: str
lines: List[InvoiceLine]
issued_at: datetime
paid: bool = False
@property
def total_amount(self) -> float:
return round(sum(line.total for line in self.lines), 2)
def mark_paid(self) -> None:
if self.paid:
raise ValueError(f"Invoice {self.invoice_id} is already paid.")
self.paid = True
class InvoiceRepositoryPort(Protocol):
def save(self, invoice: Invoice) -> None: ...
def find_by_id(self, invoice_id: str) -> Optional[Invoice]: ...
class NotificationPort(Protocol):
def send_payment_receipt(
self, customer_id: str, amount: float
) -> None: ...
class SettleInvoiceService:
def __init__(
self,
repository: InvoiceRepositoryPort,
notifier: NotificationPort,
) -> None:
self._repository = repository
self._notifier = notifier
def execute(self, invoice_id: str) -> bool:
invoice = self._repository.find_by_id(invoice_id)
if invoice is None:
raise ValueError(f"Invoice not found: {invoice_id}")
invoice.mark_paid()
self._repository.save(invoice)
self._notifier.send_payment_receipt(
invoice.customer_id, invoice.total_amount
)
return True
class InMemoryInvoiceRepository:
def __init__(self) -> None:
self._storage: Dict[str, Invoice] = {}
def save(self, invoice: Invoice) -> None:
self._storage[invoice.invoice_id] = invoice
def find_by_id(self, invoice_id: str) -> Optional[Invoice]:
return self._storage.get(invoice_id)
class InMemoryNotificationAdapter:
def __init__(self) -> None:
self.sent_messages: List[Dict[str, object]] = []
def send_payment_receipt(
self, customer_id: str, amount: float
) -> None:
self.sent_messages.append(
{"customer_id": customer_id, "amount": amount}
)
def main() -> None:
repo = InMemoryInvoiceRepository()
notifier = InMemoryNotificationAdapter()
service = SettleInvoiceService(repo, notifier)
inv = Invoice(
"INV-101",
"C-01",
[InvoiceLine("DevOps Audit", 1, 500.0)],
datetime(2026, 11, 9, 12, 0, 0),
)
repo.save(inv)
# Test 1: Normal settlement
service.execute("INV-101")
print("Test 1 (Normal settlement): PASS")
# Test 2: Double payment invariant
try:
service.execute("INV-101")
except ValueError:
print("Test 2 (Double payment caught): PASS")
# Test 3: Missing invoice error
try:
service.execute("INV-999")
except ValueError:
print("Test 3 (Missing invoice caught): PASS")
if __name__ == "__main__":
main()
Test 1 (Normal settlement): PASS
Test 2 (Double payment caught): PASS
Test 3 (Missing invoice caught): PASS
04. Closing the Contract Gap: Shared Contract Suites
A valid critique of in-memory fakes is the risk of Behavioral Drift. What happens if the InMemoryInvoiceRepository allows saving an invoice with a duplicate ID, while the real production PostgreSQL adapter throws a UniqueViolation database exception? If the fake does not faithfully mirror production behavior, tests give false confidence.
The architectural solution is a Shared Contract Test Suite:
- Author a single generic test suite defining the expected behavioral contract for the repository port (e.g., verifying that finding an unknown entity returns
None, saving an aggregate updates existing rows, and duplicate keys raise domain exceptions). - Execute this identical test suite against the in-memory fake adapter in fast local unit tests.
- Execute the exact same test suite against the real PostgreSQL adapter in CI against a real database container.
Simulating Transient Failures and Edge Conditions Beyond standard persistence operations, in-memory fakes provide an unparalleled mechanism for testing failure handling, retries, and compensation logic that are exceedingly difficult to trigger reliably against live databases:
- Simulating Transient Network Outages: A fake notification adapter can be configured with a flag (
notifier.simulate_network_failure = True) to raise timeout exceptions on the first two attempts and succeed on the third. This allows unit tests to assert that use-case retry policies, exponential backoff delays, and dead-letter queue routing function properly without waiting for real TCP socket timeouts. - Simulating Concurrent Optimistic Locking Conflicts: An in-memory repository fake can track entity version counters. If a test simulates two concurrent use-case threads attempting to mutate the same aggregate concurrently, the fake raises an
OptimisticLockingConflictErroron the second commit, allowing developers to verify conflict resolution logic deterministically in milliseconds. - Deterministic Clock Injection: Ports that require timestamp verification should inject a
ClockPortrather than calling system time functions likedatetime.now()directly. The in-memory clock adapter allows unit tests to freeze time or fast-forward across expiration windows with zero sleep delays.
The Inverted Testing Pyramid in Hexagonal Systems By adopting in-memory adapters validated by contract suites, the traditional testing pyramid is righted. Teams run ninety percent of their test portfolio as pure in-memory use-case unit tests that run in milliseconds, nine percent as adapter contract verification suites against isolated testcontainers, and only one percent as true end-to-end smoke tests against staging environments.
This guarantees that the fake adapter and the production adapter adhere to identical behavioral semantics, eliminating drift while preserving blistering test execution speeds.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.