Integration Testing: API Contracts, Testcontainers & Database Boundaries

Last Audited: 2026-08-18
Tier-1 Platform Core
In Plain Language

Subsystem boundary verification, consumer-driven contract testing (Pact), ephemeral test databases (Testcontainers), and mock HTTP harnesses.

Integration Testing: Verifying Service Boundaries Without Flakiness

While unit tests verify individual functions, integration tests verify the boundaries where components collaborate: database transactions, message broker pub/sub queues, and inter-service HTTP/gRPC contracts. Integration tests represent 15% to 20% of the testing pyramid, striking a balance between behavioral confidence and execution speed.

Three Core Integration Testing Patterns

1. Consumer-Driven Contracts (Pact)

API consumers publish their request/response expectations as a contract JSON. Providers verify their API against this contract in CI without deploying the consumer.

Eliminates brittle end-to-end integration environments.

2. Testcontainers Isolation

Spins up lightweight, real Docker instances of PostgreSQL, Redis, or Kafka during test runs and discards them immediately upon test completion.

Zero shared database contamination between test suites.

3. Deterministic Mock Servers (WireMock / MSW)

Intercepts outbound network calls to third-party payment or EHR gateways, returning deterministic mock payloads with configurable network latency and error codes.

Guarantees 100% offline, repeatable CI execution.

Consumer-Driven Contract Workflow (Pact)

TypeScript / Pact.js API Contract Verification
import { PactV3, MatchersV3 } from '@pact-foundation/pact';

const provider = new PactV3({
  consumer: 'WebFrontend',
  provider: 'PatientTelemetryService',
});

describe('Pact with Telemetry Service', () => {
  it('returns valid telemetry readings for authorized patient', async () => {
    provider
      .given('Patient 402 has active telemetry stream')
      .uponReceiving('a request for telemetry summary')
      .withRequest({
        method: 'GET',
        path: '/api/v1/patients/402/telemetry',
        headers: { Authorization: MatchersV3.like('Bearer valid-token') },
      })
      .willRespondWith({
        status: 200,
        headers: { 'Content-Type': 'application/json' },
        body: {
          patientId: MatchersV3.uuid('402e4567-e89b-12d3-a456-426614174000'),
          heartRateBpm: MatchersV3.integer(72),
          status: MatchersV3.string('NORMAL'),
        },
      });

    await provider.executeTest(async (mockserver) => {
      const res = await fetch(`${mockserver.url}/api/v1/patients/402/telemetry`, {
        headers: { Authorization: 'Bearer valid-token' },
      });
      const data = await res.json();
      expect(data.status).toBe('NORMAL');
    });
  });
});
Try This With AI: API Contract & Testcontainer Generator
Integration Prompt

Use this prompt to generate Pact contract definitions and Testcontainers setup hooks for your services:

"Act as a Senior Backend Integration Architect. Analyze the following OpenAPI / TypeScript endpoint schema: [PASTE SCHEMA / ROUTE]. Write a complete integration test using Testcontainers (PostgreSQL) and Pact.io: (1) Setup isolated container with database migrations, (2) Define consumer expectation contract, (3) Execute transaction rollback test, and (4) Assert error handling when database connection pool exhausts."

Community Discussion & Feedback

Attributed peer feedback and official Netspective architecture notes.

Was this documentation helpful?(100% found this helpful • 0 ratings)

Leave Feedback or Question

○ Loading user info...
0/2000 chars

Discussion (0)

Loading discussion thread...