Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 20 min · revision 1

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

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.

02. Authoring Stateful In-Memory Adapters

An in-memory fake adapter implements the exact same driven port interface as the production infrastructure adapter. Instead of generating SQL statements or emitting TCP packets over the network, it stores domain entities in native in-memory data structures (such as Python dictionaries or JavaScript Maps).

Key Principles for Reliable In-Memory Fakes:

  • Faithful Contract Emulation: The fake must reproduce the behavioral semantics of the port interface, including returning None / undefined when an aggregate is missing, and enforcing unique constraint checks.
  • Zero External Libraries: The fake contains no ORM code, database drivers, or filesystem interactions. It runs entirely inside volatile RAM memory.
  • State Inspection Seams: In-memory fakes can expose lightweight inspection attributes (such as sent_messages on a notification fake) that allow test assertions to verify outbound side effects cleanly without spy mocks.
  • Independent Deep Copying: When saving or retrieving aggregates from an in-memory dictionary, fakes should return deep copies or snapshot representations. If a fake returns a direct mutable memory reference, tests can inadvertently modify fake state without calling save(), masking bugs where use cases forget to persist modified domain aggregates.

The Economic Value of Sub-Second Test Suites The primary driver for in-memory fakes is psychological and economic: developer feedback loops. When a test suite executes in three hundred milliseconds, developers run it after every keystroke. Test-Driven Development (TDD) becomes natural and effortless.

Conversely, when a test suite requires thirty seconds to spin up database containers and run schema migrations, developers stop running tests locally. They push untested code to CI, shifting bug detection downstream where investigation and context-switching costs multiply tenfold.

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.

Testing domain invariants with in-memory adapters in Python
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()
Expected output from in-memory invariant tests
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 OptimisticLockingConflictError on the second commit, allowing developers to verify conflict resolution logic deterministically in milliseconds.
  • Deterministic Clock Injection: Ports that require timestamp verification should inject a ClockPort rather than calling system time functions like datetime.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.

Practice check · 2 questions

Practice check

Validate your understanding of testing the core with in-memory adapters and contract test suites.

Q1. What is the primary advantage of testing hexagonal use cases with in-memory fake adapters instead of mocking frameworks?
Q2. How do engineering teams prevent behavioral drift between in-memory fake adapters and production SQL database adapters?
Practice only: not graded, not saved, not evidence.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check