TS·116
Integration Testing
Testing your code against real boundaries: why mocks aren't enough, databases (migrations, transactions, isolation, per-test cleanup), message brokers, HTTP clients and servers (WireMock, httptest, MockServer), file systems, authentication, caches and cloud services, Testcontainers in Java, Go, Python, Rust and Node, framework support (Spring Boot service connections, Quarkus Dev Services), speed and parallelism, and ephemeral environments for pull requests.
Start here: testing against the real thing
Unit tests replace databases, queues and other services with doubles, which keeps them fast. But a double only behaves the way you think the real thing behaves. Integration tests run your code against the real dependency (a real PostgreSQL, a real broker, a realistic HTTP server) to catch the gap between what you assumed and what actually happens.
"Just use SQLite for tests" is a different database
The same table and queries, in SQLite (a popular test stand-in) and in PostgreSQL (production):
LIKE 'dal%' sqlite: ['Dal Tadka', 'dal makhani'] | postgres: ['dal makhani']
sum(price) sqlite: 450.6 | postgres: 450.60
price * 3 sqlite: 360.29999999999995 | postgres: 360.30
insert 'abc' as price: sqlite accepted it (stored as text) | postgres: InvalidTextRepresentation
SQLite's LIKE ignores case for ASCII letters; PostgreSQL's doesn't. SQLite stored the numeric(10,2) prices as floating point and accepted text in a number column; PostgreSQL kept exact decimals and refused. A search feature, a bill and a validation rule would all pass their tests on SQLite and behave differently in production. Test against the database you run.
A bug that only appears with two users at once
One tiffin left in the 1 pm slot. Two customers book at the same instant. The naive code reads the count, checks it's above zero, then decrements:
naive (read, check, update): oversold in 20/20 runs → bookings=2, left=-1
SELECT … FOR UPDATE: oversold in 0/20 runs → bookings=1, left=0
Both transactions read left = 1 before either wrote, so both booked. Locking the row with SELECT … FOR UPDATE makes the second transaction wait until the first commits, then it sees 0. No unit test with a mocked repository could ever show this; it needs a real database and real concurrency.
Keeping integration tests fast and independent
Each test must start from a known state. Four ways to reset, 5 inserts plus a count per test:
rollback per test: 1.0 ms/test
truncate per test: 7.0 ms/test
new connection + delete: 10.1 ms/test
fresh database from template: 120.3 ms/test
Wrapping each test in a transaction and rolling it back is the cheapest; a fresh database per test is the most isolated and over 100 times slower. Many suites use rollback by default and a fresh database only for tests that need to commit (like the double-booking test).
Faking a remote service realistically
A fake payment provider that can answer normally, fail, return garbage or hang:
provider ok timeout=1.0 → paid in 0.02 s
provider 500 timeout=1.0 → unknown (HTTP 500) in 0.00 s
provider badjson timeout=1.0 → unknown (bad body) in 0.00 s
provider slow timeout=None → paid in 3.00 s
provider slow timeout=1.0 → unknown (timeout) in 1.00 s
Without a timeout, a 3-second hang becomes a 3-second hang in your service (and with a stuck provider, forever). Testing the failure modes, not just the happy path, is where an HTTP fake earns its keep.
How deep to go in integration testing
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain why mocks aren't enough and what integration tests cover |
| L2 | Write integration tests against a real database and an HTTP fake with clean state per test |
| L3 | Explain isolation strategies, transactions and concurrency in tests, Testcontainers and service virtualisation |
| L4 | Find bugs that only appear against real dependencies: dialects, races, timeouts, serialisation |
| L5 | Design a project's integration-test environment, data management and CI setup |
| L6 | Provide shared test infrastructure and standards across many teams |
Why integration tests
Unit tests with doubles verify your logic assuming your dependencies behave as you think. Most production bugs in service code live at the boundaries:
- SQL that's valid in your head but not in Postgres (or behaves differently from H2/SQLite).
- Migrations that fail on real data types, constraints and indexes.
- Transaction isolation and locking behaviour; unique-constraint violations under concurrency.
- Serialisation mismatches with a broker or HTTP API (field names, time formats, nulls).
- Timeouts, retries, connection pool exhaustion, TLS configuration.
- Authentication and authorisation wiring (filters, middleware, token validation).
- Cache invalidation and TTL behaviour.
Integration tests exercise your code together with real instances of these dependencies (or high-fidelity substitutes), usually as medium-sized tests on one machine (chapter 114).
Testcontainers
Testcontainers starts real dependencies in throwaway Docker containers from test code, with random ports, readiness checks and automatic cleanup (via the Ryuk reaper container). Libraries exist for Java, Go, Python, Node, Rust, .NET, Ruby and more, with modules for Postgres, MySQL, Kafka, Redpanda, RabbitMQ, Redis, MongoDB, Elasticsearch, LocalStack (AWS), Keycloak, Ollama, and many others.
Needs: a Docker-compatible runtime (Docker Engine, Docker Desktop, Podman, Colima, Rancher Desktop) or Testcontainers Cloud for CI without Docker-in-Docker.
Testcontainers for Java 2.x renamed modules with a testcontainers- prefix (org.testcontainers:testcontainers-postgresql), moved classes to per-module packages (org.testcontainers.postgresql.PostgreSQLContainer) and removed JUnit 4 support.
// Java: JUnit 6 + Testcontainers 2.x, plain JDBC repository test
@Testcontainers
class OrderRepositoryIT {
@Container
static final PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18-alpine");
OrderRepository repo;
@BeforeEach
void setUp() {
var ds = new PGSimpleDataSource();
ds.setUrl(postgres.getJdbcUrl());
ds.setUser(postgres.getUsername());
ds.setPassword(postgres.getPassword());
Flyway.configure().dataSource(ds).cleanDisabled(false).load().clean(); // reset per test
Flyway.configure().dataSource(ds).load().migrate(); // real migrations
repo = new OrderRepository(ds);
}
@Test
void rejectsDuplicateIdempotencyKey() {
repo.insert(new Order("o1", "key-1"));
assertThatThrownBy(() -> repo.insert(new Order("o2", "key-1")))
.isInstanceOf(DuplicateKeyException.class); // the real unique constraint
}
}
// Go: testcontainers-go Postgres module
func TestOrderRepo(t *testing.T) {
ctx := context.Background()
pg, err := postgres.Run(ctx, "postgres:18-alpine",
postgres.WithDatabase("app"),
postgres.WithUsername("app"), postgres.WithPassword("secret"),
postgres.BasicWaitStrategies(),
)
testcontainers.CleanupContainer(t, pg)
if err != nil { t.Fatal(err) }
dsn, err := pg.ConnectionString(ctx, "sslmode=disable")
if err != nil { t.Fatal(err) }
db := mustOpen(t, dsn)
mustMigrate(t, db) // run real migrations
repo := NewOrderRepo(db)
if err := repo.Insert(ctx, Order{ID: "o1", IdemKey: "k1"}); err != nil { t.Fatal(err) }
err = repo.Insert(ctx, Order{ID: "o2", IdemKey: "k1"})
if !errors.Is(err, ErrDuplicate) { t.Fatalf("want ErrDuplicate, got %v", err) }
}
# Python: testcontainers-python with a session-scoped pytest fixture
import pytest
from testcontainers.postgres import PostgresContainer
from sqlalchemy import create_engine
@pytest.fixture(scope="session")
def engine():
with PostgresContainer("postgres:18-alpine", driver="psycopg") as pg:
eng = create_engine(pg.get_connection_url())
run_migrations(eng) # e.g. alembic upgrade head
yield eng
@pytest.fixture
def conn(engine):
with engine.connect() as c:
tx = c.begin()
yield c
tx.rollback() # isolate each test by rolling back
def test_duplicate_idempotency_key(conn):
repo = OrderRepo(conn)
repo.insert(Order("o1", "k1"))
with pytest.raises(DuplicateKey):
repo.insert(Order("o2", "k1"))
// Rust: testcontainers + testcontainers-modules (async runner) with sqlx
use testcontainers_modules::{postgres::Postgres, testcontainers::runners::AsyncRunner};
#[tokio::test]
async fn rejects_duplicate_idempotency_key() -> anyhow::Result<()> {
let node = Postgres::default().with_tag("18-alpine").start().await?;
let url = format!("postgres://postgres:postgres@{}:{}/postgres",
node.get_host().await?, node.get_host_port_ipv4(5432).await?);
let pool = sqlx::PgPool::connect(&url).await?;
sqlx::migrate!("./migrations").run(&pool).await?;
let repo = OrderRepo::new(pool);
repo.insert("o1", "k1").await?;
assert!(matches!(repo.insert("o2", "k1").await, Err(RepoError::Duplicate)));
Ok(())
} // container stops when `node` is dropped
// Node: @testcontainers/postgresql with Vitest
import { PostgreSqlContainer, StartedPostgreSqlContainer } from "@testcontainers/postgresql";
import { beforeAll, afterAll, test, expect } from "vitest";
let pg: StartedPostgreSqlContainer;
beforeAll(async () => {
pg = await new PostgreSqlContainer("postgres:18-alpine").start();
await migrate(pg.getConnectionUri());
}, 60_000);
afterAll(async () => { await pg.stop(); });
test("rejects duplicate idempotency key", async () => {
const repo = new OrderRepo(pg.getConnectionUri());
await repo.insert({ id: "o1", idemKey: "k1" });
await expect(repo.insert({ id: "o2", idemKey: "k1" })).rejects.toThrow(DuplicateKeyError);
});
Framework support
- Spring Boot:
@ServiceConnectionon a container field auto-configures the datasource, Kafka, Redis, etc. from the container;@SpringBootTest(webEnvironment = RANDOM_PORT)starts the real server; test slices (@DataJpaTest,@WebMvcTest) load only part of the context. Spring Boot can also start the same containers in development (spring-boot-testcontainers, Docker Compose support). - Quarkus: Dev Services start containers automatically in dev and test mode when no URL is configured.
- Micronaut: Test Resources.
- .NET:
WebApplicationFactory+ Testcontainers.
// Spring Boot: full HTTP + real DB + real Kafka
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class CheckoutApiIT {
@Container @ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18-alpine");
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka-native:4.1.0");
@Autowired TestRestTemplate http;
@Test
void placingAnOrderPublishesEvent() {
var res = http.postForEntity("/orders", new PlaceOrder("book", 1), OrderDto.class);
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.CREATED);
// consume from the real topic and assert the OrderPlaced event arrives (with a timeout)
}
}
Databases
Database integration tests should use the same engine and version as production. In-memory substitutes (H2 pretending to be Postgres, SQLite instead of MySQL) differ in SQL dialect, types, constraint behaviour, locking and query planning, so they give false confidence.
Keeping tests isolated
| Strategy | How | Trade-offs |
|---|---|---|
| Transaction rollback per test | Begin a transaction, run the test, roll back | Very fast; but code that manages its own transactions, commits, or uses multiple connections escapes it |
| Truncate/clean tables before each test | TRUNCATE … CASCADE or Flyway clean + migrate |
Simple; slower with many tables |
| Template databases | Migrate once, CREATE DATABASE test_n TEMPLATE app_template per test or worker |
Fast fresh DBs in Postgres; good for parallel tests |
| Unique data per test | Each test uses its own tenant/IDs; no cleanup | Parallel-friendly; data accumulates |
| Container per test class | Fresh container | Strong isolation, slowest |
Test the things that only the real database can tell you: migrations (forward, and on realistic data), constraints, query results and ordering, ON CONFLICT upserts, transaction isolation and locking (two concurrent transactions in the test), JSON operators, full-text search, and query plans for critical queries (EXPLAIN in a test to catch accidental sequential scans).
Message brokers
Testing producers and consumers against a real Kafka (or Redpanda), RabbitMQ, NATS or a cloud emulator (LocalStack SQS/SNS, the Pub/Sub emulator):
- Verify serialisation and schemas (with a real Schema Registry container where used).
- Verify consumer behaviour: offsets committed after processing, retries and dead-letter routing for poison messages, idempotent handling of redelivered messages (Vol. 5 ch. 68).
- Asynchronous assertions need polling with timeouts, not
sleep: Awaitility (Java),assert.Eventually(Go testify),tenacity/polling helpers (Python),vi.waitFor(Vitest).
// Awaitility: wait until the consumer has processed the event
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100))
.untilAsserted(() -> assertThat(projectionRepo.find("o1")).hasValueSatisfying(
p -> assertThat(p.status()).isEqualTo("PLACED")));
HTTP boundaries
Testing your server
Start your real HTTP stack (routing, middleware, serialisation, auth filters) in-process on a random port, or via the framework's in-memory test client:
// Go: httptest runs the real handler stack on a loopback server
func TestCreateOrderAPI(t *testing.T) {
srv := httptest.NewServer(NewRouter(deps(t)))
t.Cleanup(srv.Close)
body := strings.NewReader(`{"sku":"book","qty":1}`)
req, _ := http.NewRequest("POST", srv.URL+"/orders", body)
req.Header.Set("Authorization", "Bearer "+testToken(t, "user-1"))
res, err := srv.Client().Do(req)
if err != nil { t.Fatal(err) }
if res.StatusCode != http.StatusCreated { t.Fatalf("status %d", res.StatusCode) }
}
# Python: FastAPI TestClient (or httpx.AsyncClient with ASGITransport)
from fastapi.testclient import TestClient
def test_create_order_requires_auth(app):
client = TestClient(app)
assert client.post("/orders", json={"sku": "book", "qty": 1}).status_code == 401
// Rust (axum): drive the Router as a tower Service without a socket
use tower::ServiceExt;
#[tokio::test]
async fn create_order_requires_auth() {
let app = build_router(test_state().await);
let res = app.oneshot(
http::Request::post("/orders").header("content-type", "application/json")
.body(axum::body::Body::from(r#"{"sku":"book","qty":1}"#)).unwrap()
).await.unwrap();
assert_eq!(res.status(), http::StatusCode::UNAUTHORIZED);
}
// Node: supertest against an Express/Fastify app
import request from "supertest";
test("create order requires auth", async () => {
await request(app).post("/orders").send({ sku: "book", qty: 1 }).expect(401);
});
Testing your HTTP clients
For third-party APIs you don't control, use a stub server that speaks real HTTP: WireMock (Java, also as a container usable from any language), MockServer, httptest.Server in Go, respx/pytest-httpserver in Python, wiremock-rs/httpmock in Rust, MSW (Mock Service Worker) or nock in Node. Test real behaviours: request format and headers, retries on 503, timeouts, handling of malformed responses, pagination, rate-limit responses (429 with Retry-After).
// WireMock: simulate a slow and then failing payment provider
@RegisterExtension
static WireMockExtension psp = WireMockExtension.newInstance().options(wireMockConfig().dynamicPort()).build();
@Test
void retriesOnServiceUnavailableThenSucceeds() {
psp.stubFor(post("/charges").inScenario("flaky").whenScenarioStateIs(STARTED)
.willReturn(aResponse().withStatus(503)).willSetStateTo("recovered"));
psp.stubFor(post("/charges").inScenario("flaky").whenScenarioStateIs("recovered")
.willReturn(okJson("{\"id\":\"ch_1\",\"status\":\"succeeded\"}")));
var client = new PspClient(psp.baseUrl(), Duration.ofSeconds(2));
assertThat(client.charge(Money.eur(10)).id()).isEqualTo("ch_1");
psp.verify(2, postRequestedFor(urlEqualTo("/charges")));
}
Stubs encode your assumptions about the provider; complement them with contract tests (chapter 117) where you control both sides, provider sandbox environments, and recorded real responses refreshed periodically.
File systems, auth, caches and cloud services
- File systems: use temporary directories (
t.TempDir(), pytesttmp_path, JUnit@TempDir, Rusttempfile); test permissions, missing files, large files, concurrent writers, and path handling across OSes (CI on Windows if you ship there). - Authentication: run a real identity provider in a container (Keycloak, or lightweight OIDC mock servers) to test the full token flow and validation; or mint test JWTs with a test key pair that the service trusts only in test configuration. Test that endpoints reject missing, expired, wrong-audience and wrongly signed tokens.
- Caches: Redis/Valkey containers; test TTLs (with short TTLs or controllable time), invalidation on writes, behaviour when the cache is down (the service should degrade, not fail).
- Cloud services: LocalStack (AWS emulation: S3, SQS, DynamoDB, Lambda…), Azurite (Azure Storage), Google emulators (Pub/Sub, Firestore, Spanner, Bigtable), MinIO for S3-compatible storage. Emulators differ from real services in edge cases (IAM, consistency, limits), so also run a smaller suite against real cloud accounts in a sandbox.
Speed and reliability
Integration tests are slower than unit tests; keep them practical:
- Reuse containers across tests in a run (static/session-scoped containers, singleton pattern), and isolate via data strategies above rather than restarting.
- Parallelise across workers with separate databases/schemas per worker.
- Pre-pull images in CI, pin image tags (or digests), and use small images (
-alpine,kafka-native). - Use readiness waits (log message, health check, port) rather than sleeps; Testcontainers modules include sensible wait strategies.
- Name integration tests distinctly (
*IT.javawith Maven Failsafe, Go build tags ortesting.Short(), pytest markers, Rusttests/directory) so developers can run the fast unit suite separately.
Ephemeral environments
For tests that need many services together, or for manual QA and product review, create an ephemeral environment per pull request:
- Deployed automatically on PR open (Kubernetes namespace per PR with Helm/Kustomize, Argo CD ApplicationSets with a pull-request generator; platforms such as Vercel/Netlify previews for front ends, Okteto, Signadot, Bunnyshell, Uffizzi).
- Seeded with synthetic test data; shared expensive dependencies (a staging database cluster) with per-environment databases or schemas.
- Destroyed on merge/close (and on a TTL) to control cost.
- Request-level isolation (Signadot-style "sandboxes"): deploy only the changed service and route tagged requests to it inside a shared staging environment, avoiding full copies of large systems.
Ephemeral environments make late-stage tests realistic without the "shared staging is broken again" problem, but they cost money and setup effort; most verification should still happen in fast, local integration tests.
Lab: integration tests against real dependencies
PostgreSQL 16 (local, Unix socket) through psycopg 3.3, SQLite 3 from Python's standard library, and a fake HTTP provider on http.server, all on the lab machine. A limitation: the lab has no access to a container registry, so Testcontainers couldn't pull a PostgreSQL image; the tests use a locally running PostgreSQL instead, which is what Testcontainers would start for you.
Experiment 1: the stand-in database lies
LIKE 'dal%' sqlite: ['Dal Tadka', 'dal makhani'] | postgres: ['dal makhani']
sum(price) sqlite: 450.6 | postgres: 450.60
price * 3 sqlite: 360.29999999999995 | postgres: 360.30
insert 'abc' sqlite: accepted → ('abc', 'text') | postgres: InvalidTextRepresentation
SQLite uses type affinity: a column declared numeric(10,2) stores whatever it can as integer or floating point, and anything else as text. PostgreSQL enforces the declared type exactly. Other common gaps between test and production databases: case and accent sensitivity (collations), NULL ordering, JSON operators, ON CONFLICT syntax, transaction isolation levels, time-zone handling of timestamps, and error codes your code catches. H2 in "PostgreSQL mode" narrows some gaps and leaves others. The robust answer is the same engine and major version as production, started per test run.
Experiment 2: catching a race with a real database
left = c.execute("select left_count from slots where id=1").fetchone()[0]
barrier.wait() # make both customers read before either writes
if left > 0:
c.execute("update slots set left_count = left_count - 1 where id=1")
book_naive 20 runs × 2 customers for 1 tiffin: oversold in 20/20 runs (bookings=2, left=-1)
book_locked 20 runs × 2 customers for 1 tiffin: oversold in 0/20 runs (bookings=1, left=0)
The threading.Barrier makes the race deterministic: both threads finish their read before either writes, so the bug shows every run instead of once in a thousand. Three correct fixes, each testable the same way: lock the row (FOR UPDATE), make the update conditional and check the row count (update … set left_count = left_count - 1 where id = 1 and left_count > 0), or add a constraint (check (left_count >= 0)) so the database refuses the oversell. The constraint is the strongest because it protects against every code path, including ones written later.
Experiment 3: isolation strategies, timed
rollback per test: 1.0 ms/test
truncate per test: 7.0 ms/test
new connection + delete: 10.1 ms/test
fresh database from template: 120.3 ms/test (CREATE DATABASE … TEMPLATE, then DROP)
Rollback works when the test and the code under test share one connection and the code doesn't commit; Spring's @Transactional tests and Django's TestCase use exactly this. When code commits or spans connections (background workers, the race test), use truncation or per-worker databases. With pytest-xdist or parallel JUnit, give each worker its own database (created once from a template) so parallel tests don't collide.
Experiment 4: an HTTP fake that misbehaves on demand
provider ok client timeout=1.0 → paid 0.02 s
provider 500 client timeout=1.0 → unknown (HTTP 500) 0.00 s
provider badjson client timeout=1.0 → unknown (bad body) 0.00 s
provider slow client timeout=None → paid 3.00 s
provider slow client timeout=1.0 → unknown (timeout) 1.00 s
Tools such as WireMock (Java, also standalone), httptest (Go), respx/pytest-httpserver (Python), MSW (JavaScript) and Toxiproxy (network faults, chapter 120) do the same with less code. The design lesson is in the results: the client maps every failure to an explicit "unknown" rather than raising or assuming "paid", and the caller can then retry or reconcile later. Integration tests are where you prove that mapping for each failure the provider can produce.
Try it yourself
- Add
check (left_count >= 0)and rerun the naive booking. What error does the second customer get, and how should the application report it? - Run the race test under
REPEATABLE READisolation instead of the default. What changes? - Use
pytest-xdist -n 4with one database per worker created from a template; measure the speed-up on 200 integration tests. - Make the fake provider answer slowly after sending headers (trickle the body). Does the client's timeout still fire?
Revision sheet: integration testing
Key ideas
- Purpose: verify your code against real boundaries (databases, brokers, HTTP services, file systems, caches) where doubles encode only your assumptions.
- Same engine as production: same database and major version, started per run (Testcontainers, docker compose, a CI service container).
- Clean state per test: rollback, truncate, per-worker or per-test databases; migrations applied once per run.
- Concurrency bugs need real databases and deliberate interleaving (barriers, latches) to show deterministically.
- HTTP and service fakes (WireMock, httptest, MSW, respx) for success and every failure: errors, bad bodies, slowness, resets.
- Brokers: test serialisation, ordering, redelivery and idempotent consumers against a real Kafka, RabbitMQ or NATS.
- Scope: narrow integration tests (one adapter, one dependency) are fast and precise; broad ones go toward E2E.
Numbers to remember
- Lab: rollback 1.0 ms, truncate 7.0 ms, new connection 10.1 ms, fresh template database 120 ms per test.
- Lab: naive read-check-write oversold 20/20 runs; row lock 0/20.
- Lab: no timeout turned a 3 s provider hang into a 3 s request.
Pitfalls
- SQLite or H2 standing in for PostgreSQL or MySQL.
- Tests depending on data left by other tests; shared databases between parallel workers.
- Only testing happy paths against fakes.
- Mocking your own repository layer in "integration" tests.
- Clients without timeouts.
- Slow, broad integration suites that duplicate E2E tests.
Glossary
- Testcontainers: libraries that start real dependencies in throwaway containers for tests.
- Type affinity: SQLite's loose column typing.
- Template database: a PostgreSQL database copied to create fresh ones quickly.
- Service virtualisation: simulating a dependency's API and behaviour.
- Narrow vs broad integration test: one boundary vs many components together.