100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Software Testing

Writing Integration Tests

Learn how to test the way multiple units of your system work together, catching bugs that unit tests miss at the boundaries between modules, services, and infrastructure.

Integration & E2EIntermediate9 min readJul 10, 2026
Analogies

What Integration Tests Actually Verify

Unit tests verify a single function or class in isolation, usually with all its dependencies mocked out. Integration tests instead exercise two or more real components together — a service talking to a real repository, a repository talking to a real (or realistic) database, a message handler talking to a real queue client — so that the wiring between them, not just each piece alone, is proven correct. The bugs integration tests catch are specifically the ones unit tests structurally cannot: a mismatched SQL column name, a serialization format both sides agree on in isolation but not when combined, a transaction that unit tests mock away entirely.

🏏

Cricket analogy: A unit test is like checking a bowler's action in the nets alone; an integration test is like a full net session where the bowler, keeper, and slip cordon work together, revealing timing issues — like a keeper standing up too early — that solo drills never expose.

Structuring an Integration Test Suite

A healthy integration suite scopes each test to a well-defined slice of the system — for example, one HTTP handler plus the real service layer plus a real (often containerized) database — rather than spinning up the entire application. Test setup typically follows arrange-act-assert: seed the database with known fixture rows, invoke the real code path, then assert on both the returned value and any observable side effects, such as a row actually persisted or an event actually published. Because integration tests are slower and more stateful than unit tests, teams usually keep them in a separate test project or tagged suite so CI can run fast unit tests on every commit and the heavier integration suite on a merge or nightly schedule.

🏏

Cricket analogy: A team doesn't run a full-scale practice match every single day — quick net sessions (unit tests) happen daily, while a full simulated match with fielding, batting, and bowling together (integration tests) is scheduled less often, just like tagging integration suites to run on a slower CI cadence.

javascript
// Integration test: real Express handler + real Postgres (via testcontainers)
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';

describe('POST /orders', () => {
  beforeEach(async () => {
    await pool.query('DELETE FROM orders');
    await pool.query(
      "INSERT INTO customers (id, name) VALUES ('cust_1', 'Ada Lovelace')"
    );
  });

  it('persists a new order and returns 201', async () => {
    const res = await request(app)
      .post('/orders')
      .send({ customerId: 'cust_1', items: [{ sku: 'BOOK-1', qty: 2 }] });

    expect(res.status).toBe(201);
    expect(res.body.id).toBeDefined();

    const { rows } = await pool.query(
      'SELECT * FROM orders WHERE customer_id = $1',
      ['cust_1']
    );
    expect(rows).toHaveLength(1);
    expect(rows[0].status).toBe('pending');
  });
});

Managing Test Data and Isolation

The most common source of flaky integration tests is shared, mutable state — a test that assumes an empty table but runs after another test left rows behind. The fix is deterministic setup and teardown: truncate or roll back relevant tables before each test, use uniquely generated identifiers rather than hardcoded ones, and avoid relying on execution order. Many frameworks support wrapping each test in a database transaction that's rolled back at the end, which is fast and guarantees a clean slate without the cost of recreating the schema. When tests must run in parallel against a shared database, namespacing data per test worker (e.g., a UUID prefix) avoids collisions entirely.

🏏

Cricket analogy: A groundskeeper rolls and re-marks the pitch before each match rather than trusting yesterday's wear pattern, the same way a transaction rollback resets the database to a clean state before every integration test.

Avoid testing against a shared staging database that other developers or CI jobs also write to. Non-deterministic collisions between parallel test runs are one of the top causes of 'flaky' integration tests that pass locally but fail intermittently in CI.

Choosing Real vs. Test-Double Dependencies

Not every dependency belongs in an integration test as a real instance. The rule of thumb: use the real thing for dependencies you own and control the schema/contract of (your own database, your own internal services), and use a test double — a stub, fake, or recorded fixture — for third-party systems that are slow, rate-limited, or costly to call, such as a payment gateway or an external email provider. Tools like testcontainers spin up real, ephemeral instances of Postgres, Redis, or Kafka in Docker for the duration of a test run, giving you production-like fidelity without a shared, long-lived environment to maintain.

🏏

Cricket analogy: A team practices against real bowlers from their own squad, since that's fully under their control, but uses a bowling machine to simulate an unpredictable overseas pace attack they can't fly in for daily practice, just as integration tests use real internal dependencies but fakes for costly external ones.

  • Integration tests verify that two or more real components work correctly together, catching wiring and boundary bugs unit tests structurally cannot see.
  • Scope each integration test to a well-defined slice of the system rather than the whole application, and keep the suite separate from fast unit tests.
  • Use arrange-act-assert with real fixture data, and assert on both return values and observable side effects like persisted rows or published events.
  • Flaky integration tests are usually caused by shared mutable state; fix this with per-test transaction rollback, unique identifiers, and avoiding order dependence.
  • Use real instances for dependencies you own (via tools like testcontainers); use stubs or fakes for slow, costly, or rate-limited third-party systems.
  • Run integration tests on a deliberate, slower cadence than unit tests since they are heavier and more stateful.
  • Never rely on a shared, long-lived staging database for integration tests run in parallel — collisions cause intermittent, hard-to-debug failures.

Practice what you learned

Was this page helpful?

Topics covered

#SoftwareTesting#TestingTDDStudyNotes#SoftwareEngineering#WritingIntegrationTests#Writing#Integration#Tests#Actually#Testing#StudyNotes#SkillVeris