What is module test isolation in a modular monolith?
An isolated module test exercises one module through three things only: the module's public interface, the schema or tables that module owns, and test doubles standing in for the public interfaces of the other modules it calls. It never reaches into another module's internal classes and never reads or writes another module's tables. If the billing module needs a customer, its test asks a fake implementation of the customers module's public API for one. It does not insert a row into the customers table.
The core argument for this discipline is simple. If a module's tests only pass when the whole application boots against one shared database state, the boundary exists only on the diagram. The code may sit in separate packages, but the tests show that the modules are still coupled through hidden data dependencies and incidental wiring. Those couplings tend to surface later, during a refactor or an extraction, when they are expensive to unwind.
Teams adopt isolation for three practical reasons:
- Faster feedback. A module suite that starts only its own components and tables runs in a fraction of the time a full-application boot takes, so engineers run it on every change.
- Ownership. The team that owns a module owns its tests and fixtures, and a failure points to that team's code.
- Enforceable boundaries. A test that depends on another module's internals fails, so boundary violations get caught early.
The payoff is largest for backend and platform teams running several modules in one codebase and one deploy, where shared state otherwise accumulates silently.
How does modular monolith testing work across layers?
Think of the test suite as layers that mirror the module boundaries, not the class hierarchy.
Per-module suites form the base. Each module's unit and component tests run alone, against the module's own code and its own data. When a module depends on another, the test replaces that dependency with a double at the dependency's public API: a facade, a service interface, or the in-process message contract it publishes. The double stands in for "the Billing module," not for InvoiceCalculator or TaxRuleRepository.
That distinction is the whole point. If Orders' tests mock Billing's internal classes, Orders now encodes knowledge of how Billing is built. A refactor inside Billing breaks Orders' tests even when the observable behavior is unchanged. That is the same coupling the module boundary was meant to remove, now living in your test code. Isolation belongs at module interfaces because that is the only surface other modules are allowed to depend on. Inside a module, use real collaborators wherever that is practical.
Consumer-driven contract tests sit between modules. The consumer states what it expects from a provider's interface or event payload, and the provider's suite verifies it still meets those expectations. This catches drift that per-module doubles hide.
A thin integration and end-to-end layer sits on top. It runs real modules together, but only to check what the lower layers cannot: dependency wiring, event subscriptions actually firing, and transaction boundaries that span modules. Keep this layer small, because each test here pays the full cost of shared state and slow setup.
+--------------------------------------------------------------------------+
| LAYER 3: THIN INTEGRATION / E2E (real modules, few tests) |
| [Orders] ----calls/events----> [Billing] |
| checks: DI wiring, event subscriptions fire, cross-module tx |
+--------------------------------------------------------------------------+
| LAYER 2: CONSUMER-DRIVEN CONTRACT TESTS (between modules) |
| [Orders] --expects--> [contract] <--verifies-- [Billing suite] |
| catches drift in facade signatures and event payloads |
+--------------------------------------------------------------------------+
| LAYER 1: PER-MODULE SUITES (each runs alone, own code + own data) |
| |
| +--- Orders suite --------------+ +--- Billing suite -------------+ |
| | Orders internals (real) | | BillingFacade (public API) | |
| | | | | | | |
| | v | | v | |
| | Billing API double <-- OK | | InvoiceCalculator (real) | |
| | | | TaxRuleRepository (real) | |
| | mock InvoiceCalculator <-- NO | | | |
| | (Billing internal: coupling) | | real collaborators inside | |
| +-------------------------------+ +-------------------------------+ |
+--------------------------------------------------------------------------+
Each module's suite runs alone with test doubles only at another module's public API. Consumer-driven contracts keep those doubles honest. A thin layer of real integration tests checks only wiring, event subscriptions and cross-module transactions.
How do you structure per-module test suites and test doubles?
Start by making the test tree mirror the module tree. If billing, inventory and accounts are top-level modules, each gets its own test directory beside its source, and each directory is a runnable suite with its own entry point. Anyone should be able to run "the billing tests" without knowing which files belong to billing. A shared top-level tests/ folder hides ownership and invites cross-module helpers that quietly couple suites together.
The test of whether this works is concrete: can the billing suite run with every other module absent or stubbed? Wire that into CI as a dedicated job that builds only billing plus its declared public-interface packages, then runs the suite. If it fails to compile or a test reaches into inventory internals, the boundary has leaked. This turns isolation from a guideline into a build failure.
Test doubles against public interfaces
When billing depends on inventory, its double implements inventory's published interface, such as a StockQuery port, never an internal repository or table. A fake that holds an in-memory map is usually clearer than a mock with scripted call expectations, because it behaves the same way across many tests.
Keeping doubles honest with contract tests
A fake can drift from the real implementation. To catch this, billing writes down its expectations as a contract, for example "querying an unknown SKU returns zero, not an error." The inventory suite then runs those same cases against the real StockQuery implementation. If inventory changes that behavior, inventory's build breaks first, before billing's fake becomes wrong without anyone noticing.
import unittest
from typing import Protocol
# inventory/public.py: the only inventory surface billing may import
class StockQuery(Protocol):
def available(self, sku: str) -> int: ...
# billing/tests/contracts/stock_query.py: billing states what it relies on.
# A plain mixin (not a TestCase) so it never runs on its own.
class StockQueryContract:
def make_stock_query(self, stock: dict) -> StockQuery:
raise NotImplementedError
def test_known_sku_returns_quantity(self):
self.assertEqual(self.make_stock_query({"SKU-100": 7}).available("SKU-100"), 7)
def test_unknown_sku_returns_zero_not_error(self):
self.assertEqual(self.make_stock_query({}).available("SKU-999"), 0)
# billing/tests/fakes.py: in-memory fake built against the public port only
class FakeStockQuery:
def __init__(self, stock: dict):
self._stock = dict(stock)
def available(self, sku: str) -> int:
return self._stock.get(sku, 0)
# billing suite: the fake must satisfy the contract it stands in for
class FakeStockQueryContractTest(StockQueryContract, unittest.TestCase):
def make_stock_query(self, stock):
return FakeStockQuery(stock)
# inventory/tests/test_billing_contract.py: provider runs the same cases
# against its real implementation (placeholder names), so drift breaks inventory first:
# class RealStockQueryContractTest(StockQueryContract, unittest.TestCase):
# def make_stock_query(self, stock):
# return SqlStockQuery(seed_test_db(stock))
# CI isolation job runs one module's suite alone:
# python -m unittest discover -s billing/tests -t .
A billing-owned contract mixin for inventory's public StockQuery port, run by billing against its in-memory fake and by inventory against the real implementation, so the fake cannot silently drift from real behavior.
Which database isolation strategy should each module use?
Data isolation is where module suites most often interfere with each other. Choose a strategy per code path, not per codebase.
| Strategy | Speed | Fidelity | Operational cost | Where it fails |
|---|---|---|---|---|
| Schema or table prefix per module | Fast | Medium | Low | Separates modules from each other, not tests from each other. Cross-schema foreign keys and triggers still couple suites. |
| Transaction per test, rolled back | Fastest | Low for commit paths | Low | Code that commits its own transactions. Second connections that can't see uncommitted rows. Deferred constraints and after-commit hooks never fire. Isolation-level behavior goes untested. |
| Truncate and reseed | Slow as table count grows | High | Medium | Foreign-key ordering, sequences that aren't reset, triggers on truncate. Parallel workers sharing one database will wipe each other's data. |
| Separate database per module or per worker | Fast once provisioned | Highest | High | Migration time per database, connection limits, and cleanup of orphaned databases after crashed runs. |
Rollback is cheap because nothing is ever written durably. That same property is why it lies about commit-time behavior. A deferred uniqueness check that would fail at COMMIT passes silently, and an outbox publisher wired to an after-commit hook never runs.
A practical combination:
- Use per-module schemas so ownership is visible and accidental cross-module queries fail loudly.
- Use transaction rollback for the bulk of repository and query tests.
- Tag commit-sensitive tests for a separate pool. These include outbox, retries, multi-connection reads, and trigger logic. Run that pool against a per-worker database cloned from a migrated template, and truncate only that worker's tables between tests.
How should test fixtures be owned and seeded per module?
Each module should own the factories and builders for the data it owns, and nothing else. An OrderBuilder in the orders module produces a valid order with sensible defaults. A test overrides only the fields it asserts on, for example anOrder().withStatus(PAID).build(). When a reader sees the test, they see the one fact that matters. A seed file with forty pre-inserted orders hides that fact.
The rule that keeps fixtures from recoupling modules is this: a module's fixtures never insert rows into tables another module owns. A typical violation is an orders test fixture that writes a row straight into billing.invoices so that a "has unpaid invoice" check passes. That fixture now depends on billing's column names, constraints, and invariants. When billing adds a non-null column or moves the table, orders tests break, even though no orders code changed.
To get cross-module state, go through the owner. Call billing's public API, or use a test helper that billing publishes and maintains, such as BillingTestSupport.givenUnpaidInvoice(customerId). Billing keeps the helper correct as its schema evolves. Orders depends only on the contract.
A global shared seed file is tempting because one script makes every test pass on day one. Over time, every module starts reading rows that other modules seeded. Nobody can delete or change a row without breaking tests they have never seen. Because of that, the seed file becomes a hidden, unversioned cross-module interface that the boundary checks never see.
// orders/test/OrderBuilder.ts: owned by orders, builds only orders data
export class OrderBuilder {
private status: OrderStatus = "PENDING"; // valid defaults
private customerId = "cust-0001";
withStatus(s: OrderStatus) { this.status = s; return this; }
forCustomer(id: string) { this.customerId = id; return this; }
build(): Order {
return new Order({ id: newOrderId(), customerId: this.customerId, status: this.status, lines: [aLine()] });
}
}
export const anOrder = () => new OrderBuilder();
// billing/test-support/BillingTestSupport.ts: published and maintained by billing
export const BillingTestSupport = {
async givenUnpaidInvoice(customerId: string) {
// Goes through billing's public API, so billing's invariants still apply
return billing.issueInvoice({ customerId, amountCents: 4200, dueDate: "2026-01-31" });
},
};
// orders/test/checkout.test.ts: states only the facts this test asserts on
test("blocks checkout when the customer has an unpaid invoice", async () => {
const order = anOrder().forCustomer("cust-0042").build();
await BillingTestSupport.givenUnpaidInvoice("cust-0042");
await expect(orders.checkout(order)).rejects.toThrow(UnpaidInvoiceError);
});
// COUNTER-EXAMPLE: an orders fixture that writes into billing's table.
// It depends on billing's column names and constraints, and it breaks when
// billing adds a NOT NULL column, even though no orders code changed.
async function seedUnpaidInvoiceBad(db: Db, customerId: string) {
await db.query(
"INSERT INTO billing.invoices (id, customer_id, status) VALUES ($1, $2, 'UNPAID')",
["inv-0001", customerId],
);
}
An orders-owned builder plus a billing-published test helper set up cross-module state through billing's API, contrasted with a fixture that inserts directly into billing.invoices.
How do you enforce boundaries and run module suites selectively in CI?
Discipline erodes under deadline pressure, so the boundary has to fail the build. Add an architecture test to the suite that loads the compiled code and asserts rules such as "nothing outside billing may depend on billing.internal" and "modules may only call each other through their declared API package." Where the language helps, use it directly:
- Go's
internaldirectories block imports from outside the parent tree. - Java's module descriptors export only named packages.
- C#
internalvisibility, scoped per assembly, hides implementation types. - Build tools with target visibility rules reject undeclared dependencies before tests run.
Once these checks are in place, a leak becomes a compile or build error, and the change that causes it gets rejected instead of slipping through.
That same dependency graph tells CI which suites to run. The CI step diffs the branch against the merge base, maps each changed path to its owning module through an ownership file, and adds every module that declares a dependency on it. Only those suites run on the pull request, in parallel. Shared build files or the ownership file itself trigger everything.
Selective runs only see declared dependencies. Shared tables, reflection, configuration keys, and event subscribers create edges the graph does not show. Run the full suite on merge to main and on a nightly schedule to catch them.
Illustrative estimate. Assume 10 modules at about 5 minutes each, which is 50 minutes serially. A typical change touches one module with two dependents, so it runs 15 minutes serially, or roughly 5 minutes across three parallel runners. The full 50-minute run still happens, but off the pull request's critical path.
#!/usr/bin/env bash
# Print the modules whose suites a PR must run, or ALL for a full run.
set -euo pipefail
# Diff against the merge base so unrelated commits on main are ignored.
BASE=$(git merge-base origin/main HEAD)
CHANGED=$(git diff --name-only "$BASE" HEAD)
# modules.txt line format: <path-prefix> <module> [dependent ...]
# e.g. src/billing/ billing invoicing reporting
declare -A selected=()
while IFS= read -r file; do
[[ -z "$file" ]] && continue
# Shared build config or the ownership map itself affects every module.
case "$file" in
settings.gradle|build.gradle|modules.txt|.ci/*) echo ALL; exit 0 ;;
esac
matched=false
while read -r prefix module dependents; do
[[ -z "$prefix" || "$prefix" == \#* ]] && continue
if [[ "$file" == "$prefix"* ]]; then
selected[$module]=1
# Unquoted on purpose: split the dependent list into words.
for d in $dependents; do selected[$d]=1; done
matched=true
fi
done < modules.txt
# A path nobody owns is an unknown edge; fail safe with a full run.
$matched || { echo ALL; exit 0; }
done <<< "$CHANGED"
# One module per line; CI fans these out to parallel jobs.
if (( ${#selected[@]} > 0 )); then
printf '%s\n' "${!selected[@]}" | sort
fi
A CI helper script that diffs the branch against its merge base, maps each changed path to its owning module and declared dependents through an ownership file, and falls back to a full run for shared build files or unowned paths.
When should you avoid strict module isolation, and what are the alternatives?
Strict isolation has costs. Test doubles drift from the real module unless a contract test pins them to its actual behaviour. Rollback-per-test fixtures never commit, so they miss bugs in commit hooks, deferred constraints and post-commit events. Per-module schemas and fixtures add setup time and duplicate seed data. Heavy mocking ties tests to call sequences, so harmless refactors break them. Hardening a boundary that is still moving makes every redraw cost twice, once in code and once in tests.
Isolation also cannot prove the system works. A modular monolith still runs as one process, so startup ordering, the shared connection pool and transactions that span modules need full-application tests no matter how clean the module suites are.
| Alternative | Fits when | Main cost |
|---|---|---|
| Whole-app integration tests, shared database | Boundaries are unstable or the team is small | Slower runs and order-dependent failures |
| Mainly end-to-end | Logic is thin and flows are user-driven | Slow feedback, and failures are hard to localize |
| Split into services | Modules need independent deploys or scaling | Network failures, API versioning and distributed operations |
To find hidden coupling in an existing suite, run each module suite alone, then run the full suite in randomized order. A test that passes only after another test depends on state that the earlier test left behind. Trace the shared global state behind it: singletons, static caches, the clock, environment variables and rows seeded by other tests. Expect your first parallel runs to produce a wave of failures. Most are real setup bugs, not flakiness, so fix them instead of adding retries.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to modular monolith testing, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.