Integration Testing: Types, Examples and How to Write Tests
Integration testing checks how two or more units, modules or services work together through their real interfaces, such as API calls, database queries, message queues and file systems. It catches the contract, data and configuration bugs that unit tests miss. In the test pyramid, it sits between unit tests and end-to-end tests.
This guide is for developers and SDETs who already write unit tests. You get a tested example with a real Postgres database, a CI workflow and a template to copy. For how all the test levels fit together, see the QA testing guide.
What is integration testing?
The ISTQB glossary defines integration testing as "a test level that focuses on interactions between components or systems." In practice, you run your code against the real thing at a boundary. That can be a database, an HTTP stack, a queue, or a faithful stand-in for a service you don't own.
Take a checkout. Unit tests prove the price math. An integration test proves the order service saves the order in Postgres, sends the right amount to the payment client and stores the result.
What integration tests catch that unit tests miss
- Wrong contracts. One service sends
customerId, and the other readscustomer_id. - Serialization. A date goes out in local time, or money goes out as a float.
- Schema drift. A migration renames a column that a query still uses.
- Config. A wrong connection string or a missing environment variable.
- Timeouts and retries. A slow service with no timeout ties up workers. A retry without an idempotency key charges a card twice.
- Auth between services. An expired token, a missing OAuth scope or clock skew.
Unit testing vs integration testing vs end-to-end testing
| Unit test | Integration test | End-to-end test | |
|---|---|---|---|
| Scope | One function or class | Two or more parts across a real interface | A full user journey through the stack |
| Dependencies | All replaced by doubles | Real for what you own, doubles for the rest | All real, or vendor sandboxes |
| Speed | Milliseconds | Milliseconds to seconds, plus startup | Seconds to minutes |
| Flakiness risk | Low | Medium | High |
| Example | Price math for 2 items | POST /orders saves a paid order | A shopper signs in, pays and sees the receipt |
Push each check down to the lowest level that can catch the bug. End-to-end tests prove a journey works, but they are slow and hard to debug, so keep them for the few journeys that earn money. For those, see the guide to end-to-end testing.
Layout bugs need a third check: visual regression testing, which compares screenshots.

Types of integration testing
The types of integration testing describe the order in which you join modules. Big bang joins them all at once. Incremental testing joins them step by step: top-down, bottom-up or both.
Big bang integration testing
Big bang joins all modules first, then tests the whole system in one go. It needs no stubs or drivers, which suits small systems where every module is ready at the same time. The catch: when ten modules join at once, a failure could come from any link between them.
Top-down integration testing
Top-down testing starts with the top modules, such as the API layer, and works down. Stubs, which are stand-ins that return canned answers, replace lower modules that are not ready yet. Use it when the main flows carry the most risk, but know that a stub unlike the real module hides bugs until the swap.
Bottom-up integration testing
Bottom-up testing starts with the lowest modules, such as data access, and works up. Drivers, which are code that calls a module and checks the result, stand in for missing callers. Today the test framework is the driver, so a test that calls a repository against a real database is a bottom-up test.
Sandwich (hybrid) integration testing
Sandwich testing runs top-down and bottom-up at the same time and meets in the middle layer. It suits large systems where different teams own the top and the bottom. It also needs both stubs and drivers.
| Approach | Starts with | Stand-ins | Best for |
|---|---|---|---|
| Big bang | All modules at once | None | Small systems, prototypes |
| Top-down | Top modules (API, workflow) | Stubs for lower modules | Risky main flows |
| Bottom-up | Bottom modules (data, core) | Drivers for upper modules | Critical data layers |
| Sandwich | Top and bottom together | Stubs and drivers | Large layered systems |
Most teams now integrate in small steps on every pull request, so these approaches matter most when you join big pieces. Which levels you run belongs in your test strategy. Record the integration order in the test plan, so everyone knows which stubs and drivers to build.

Narrow vs broad integration tests
In his IntegrationTest entry, Martin Fowler splits integration tests in two. Narrow tests exercise only the code that talks to another service, with a test double in its place. Broad tests need live versions of every service and a full test environment.
Write most of your suite as narrow tests. Keep the doubles honest with contract tests, and add a few broad tests before a release.
Component integration vs system integration testing (SIT)
Component integration testing checks parts of one system together, such as your API, database and cache. Developers usually own it, and CI runs it.
System integration testing (SIT) checks your system with other systems, such as a payment provider or a CRM. QA usually runs it on staging, against vendor sandboxes.
Test doubles: stubs, mocks, fakes and when to use the real thing
Test doubles replace what you don't want to run for real. Gerard Meszaros named the family in his book xUnit Test Patterns. Pick the simplest one that still tests what you care about.
| Option | What it does | Use it when | Watch out for |
|---|---|---|---|
| Stub | Returns canned answers | You need a fixed reply, such as a 404 | It drifts from the real API |
| Mock | Expects certain calls and fails otherwise | The call is the outcome, such as an email sent | Tests that mirror the code |
| Fake | A simple working version, such as an in-memory gateway | You need state across calls | It can have its own bugs |
| Real, in a container | The actual dependency, started for the test | You own it: your database, queue or cache | Startup time, needs Docker |
| Vendor sandbox | The provider's test environment | Final checks with a third party | Rate limits, shared data, outages |
- Own it, run it. Your database, queue and cache run for real in a container. A mock of your own database tests the mock, not your SQL.
- Don't own it, double it at the edge. Wrap each third-party API in a thin client, and double that client.
- Prefer doubles that speak HTTP. WireMock or Mock Service Worker still exercise your HTTP client, headers and timeouts.
- Check each double against the real thing with a contract test or a scheduled sandbox run.
How to write an integration test in 6 steps
- Pick one boundary, such as "orders API to Postgres over SQL". One boundary per test makes a failure easy to place.
- Decide what is real and what is doubled. Below, Express and Postgres are real, and the payment provider is a fake.
- Set up data the test owns. Start the dependency, run your real migrations and seed only the rows you need. Testcontainers starts a throwaway Postgres in Docker.
- Act through the real interface: a real HTTP request or a public function, never a private helper.
- Assert on outputs and side effects: the status, the body, the database rows and the calls to doubles. A 201 alone proves little.
- Clean up. Truncate tables, roll back a transaction or restore a snapshot between tests, and stop containers at the end.
Integration test example: an orders API with a real Postgres
This complete TypeScript test uses Express, pg, Vitest, Supertest and Testcontainers. It passes on Express 5, Vitest 5, Testcontainers 12 and Postgres 18. You need Node and a running Docker engine.
npm install express pg
npm install -D vitest supertest @testcontainers/postgresql @types/express @types/pg @types/supertest-- db/schema.sql
CREATE TABLE products (sku text PRIMARY KEY, price_cents integer NOT NULL);
CREATE TABLE orders (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL REFERENCES products (sku),
quantity integer NOT NULL CHECK (quantity > 0),
total_cents integer NOT NULL,
status text NOT NULL
);The app takes its database pool and payment client as arguments, so a test can pass in its own:
// src/app.ts
import express from 'express';
import type { Pool } from 'pg';
export interface PaymentGateway {
// orderId doubles as the idempotency key, so a retry never charges twice
charge(input: { orderId: number; amountCents: number; token: string }): Promise<{ ok: boolean }>;
}
export function createApp(db: Pool, payments: PaymentGateway) {
const app = express();
app.use(express.json());
app.post('/orders', async (req, res) => {
const { sku, quantity, paymentToken } = req.body;
if (!Number.isInteger(quantity) || quantity < 1) {
res.status(422).json({ error: 'quantity must be at least 1' });
return;
}
const product = await db.query('SELECT price_cents FROM products WHERE sku = $1', [sku]);
if (product.rows.length === 0) {
res.status(404).json({ error: 'unknown sku' });
return;
}
const totalCents = product.rows[0].price_cents * quantity;
const inserted = await db.query(
"INSERT INTO orders (sku, quantity, total_cents, status) VALUES ($1, $2, $3, 'pending') RETURNING id",
[sku, quantity, totalCents],
);
const id = inserted.rows[0].id;
const { ok } = await payments.charge({ orderId: id, amountCents: totalCents, token: paymentToken });
const status = ok ? 'paid' : 'payment_failed';
await db.query('UPDATE orders SET status = $1 WHERE id = $2', [status, id]);
res.status(ok ? 201 : 402).json({ id, status, totalCents });
});
return app;
}The test checks the response, the charge and the saved row:
// test/orders.int.test.ts
import { readFileSync } from 'node:fs';
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import type { Express } from 'express';
import { Pool } from 'pg';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createApp, type PaymentGateway } from '../src/app';
// Fake payment provider that records every charge
class FakePayments implements PaymentGateway {
charges: { orderId: number; amountCents: number; token: string }[] = [];
async charge(input: { orderId: number; amountCents: number; token: string }) {
this.charges.push(input);
return { ok: input.token !== 'tok_declined' };
}
}
let container: StartedPostgreSqlContainer;
let db: Pool;
let payments: FakePayments;
let app: Express;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:18-alpine').start();
db = new Pool({ connectionString: container.getConnectionUri() });
await db.query(readFileSync('db/schema.sql', 'utf8'));
}, 120_000);
beforeEach(async () => {
await db.query('TRUNCATE orders, products RESTART IDENTITY');
await db.query("INSERT INTO products (sku, price_cents) VALUES ('TEST-100', 1999)");
payments = new FakePayments();
app = createApp(db, payments);
});
afterAll(async () => {
await db?.end();
await container?.stop();
});
describe('POST /orders', () => {
it('charges the card and stores a paid order', async () => {
const res = await request(app)
.post('/orders')
.send({ sku: 'TEST-100', quantity: 2, paymentToken: 'tok_visa' })
.expect(201);
expect(res.body).toEqual({ id: expect.any(Number), status: 'paid', totalCents: 3998 });
expect(payments.charges).toEqual([{ orderId: res.body.id, amountCents: 3998, token: 'tok_visa' }]);
const saved = await db.query('SELECT status, total_cents FROM orders WHERE id = $1', [res.body.id]);
expect(saved.rows).toEqual([{ status: 'paid', total_cents: 3998 }]);
});
});Run it with npx vitest run test/orders.int.test.ts. Why it is built this way:
- Real schema, real engine. It uses the same Postgres major version as production, so a renamed column or a broken constraint fails here.
- A fake at the edge. The fake records each charge, so the test checks the amount and the idempotency key without a third party.
- Clean state per test. TRUNCATE with RESTART IDENTITY keeps tests independent of their order.
- One container per file. Postgres takes a few seconds to start, too slow to repeat for every test.
Testcontainers also exists for Java, Python, Go and .NET.

Tired of plain screenshots? Try ScreenSnap Pro.
Beautiful backgrounds, pro annotations, GIF recording, and instant cloud sharing, all in one app. Pay $34 once, own it forever.
See pricing and featuresAPI integration testing example
An API integration test sends a real request, then checks the status, the body, the database side effects and the calls to other services. Cover the failure cases too.
| Case | Request | Expected response | Side effects to check |
|---|---|---|---|
| Paid order | quantity 2, tok_visa | 201, status paid | One paid row, one charge of 3998 |
| Declined card | quantity 1, tok_declined | 402, status payment_failed | One payment_failed row |
| Bad input | quantity 0 | 422 with an error | No charge, no row |
| Slow provider | The fake waits past your timeout | Your timeout rule, such as 504 | At most one charge |
The slow case tests a latency budget, which is a non-functional requirement. Here is the bad-input case, added to the same describe block:
it('rejects quantity 0 before charging or writing', async () => {
const res = await request(app)
.post('/orders')
.send({ sku: 'TEST-100', quantity: 0, paymentToken: 'tok_visa' })
.expect(422);
expect(res.body).toEqual({ error: 'quantity must be at least 1' });
expect(payments.charges).toHaveLength(0);
const count = await db.query('SELECT count(*)::int AS n FROM orders');
expect(count.rows[0].n).toBe(0);
});A toEqual check on the whole body fails if a field is renamed, changes type or leaks out. The count query casts to int because pg returns Postgres bigints as strings. That kind of type surprise is what integration tests exist to catch.
Contract testing in brief
Doubles can drift from the service they copy, and contract tests close that gap. ISTQB describes contract testing as integration testing that checks each interface is used the way its contract says. A widely used open-source tool, Pact, uses consumer-driven contracts:
- The consumer's tests run against a Pact mock provider and record what they send and need back.
- Passing tests write a pact file: the contract, as examples.
- The provider's CI replays each request against the real provider and checks the responses.
- A Pact Broker shares the files and tells each team if a version is safe to deploy.
Pact fits internal services where you control both sides, not public APIs or vendors that won't run it. It checks the shape of messages, not business rules, so the provider still needs its own tests.

Integration testing in CI
Integration tests protect you only if they run before the merge.
- Run them on every pull request as required checks. Name the suites that cover the change in your pull request template.
- Split suites by file name. End integration files in
.int.test.tsand give each suite an npm script. - Run in parallel. Vitest runs files in parallel workers, and
--shardsplits a suite across CI jobs. - Keep containers warm. Start Postgres once per file, or once per run with Vitest's globalSetup, and reset data instead of restarting. The Postgres module can also snapshot a migrated database and restore it.
- Tag slow suites and run them nightly. Vitest 4.1 and later can filter tests by tag.
- Pin image tags such as
postgres:18-alpine, and fix flaky tests within a day.
GitHub-hosted Ubuntu runners include Docker, so Testcontainers works there with no setup. Add two scripts, then a workflow that runs the suite in two shards:
"scripts": {
"test:unit": "vitest run --exclude \"**/*.int.test.ts\"",
"test:int": "vitest run .int.test"
}name: tests
on: pull_request
jobs:
integration:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
shard: [1, 2]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: lts/*
cache: npm
- run: npm ci
- run: npm run test:int -- --shard=${{ matrix.shard }}/2Each shard needs at least one test file. After a deploy, a short smoke test checks the release itself, but it does not replace this suite.
Debugging failing integration tests
An integration test fails at a boundary, so your evidence has to show both sides.
- Correlation IDs. Pass a request ID in a header such as
X-Request-IDortraceparent, log it in every service and print it in the failure message. - Request and response capture. Log both on failure, with tokens masked. When a contract drifts, paste the expected and actual JSON into a text compare tool.
- Container logs. Run with
DEBUG=testcontainers:containersto see errors such as a failed constraint.
Some integrations fail in a browser instead: a payment sandbox page, an OAuth consent screen or a redirect loop. Capture the error state with the URL and build number in view, plus the failing request from DevTools. Before you share a HAR file, open it in a free HAR viewer that flags cookies and tokens and saves a sanitized copy.
Cover tokens, emails and card numbers with a solid box, since blur and pixelate can be reversed. Attach the files to the defect with the bug report template or a GitHub issue template, so the evidence lasts as long as the ticket.
ScreenSnap Pro covers this capture on Mac and Windows: callouts on the error, a filled rectangle over tokens, OCR to copy an error ID and screen recording for a redirect loop. Scrolling Capture grabs a long log page as one image: select an area, click Start Capture, scroll down, then click Finish.

Integration test case template
This template adds what a test case template for one feature lacks: the boundary, what is real, what is doubled and the side effects.
## Integration test: [ID] [short title]
Requirement: [REQ-ID] · Priority: [P1 to P3] · Owner: [name]
Boundary: [component A] to [component B] over [HTTP, SQL, queue]
Real: [what runs for real, with versions]
Doubled: [dependency · stub, mock, fake or sandbox]
Data: [seed rows, accounts, flags]
Trigger: [request, message or job]
Expected response: [status · body or schema]
Expected side effects: [rows, messages, calls to doubles]
Failure cases: [timeout · error · bad input · duplicate]
Cleanup: [truncate, roll back, delete]
Evidence on failure: [correlation ID · request and response · screenshot]Add the requirement ID, so the requirements traceability matrix shows what each boundary covers.
Common integration testing mistakes
- Testing through the UI. A browser test for an API rule is slow and flaky. Test the boundary directly.
- Shared state. Tests that share rows or a staging database pass alone and fail together.
- Over-mocking. A mocked database tests the mock, so run what you own for real.
- Ignoring timeouts and retries. Test a hanging fake, a 503 and a dropped connection. Check that a retry reuses the idempotency key.
- Fixed sleeps. Poll for async results with a deadline instead of sleeping.
- Status-only checks. A 200 with the wrong body or no database write is still a bug.
Frequently Asked Questions
Start with one boundary this sprint
Pick the boundary that broke most recently, such as the API and its database. Write one narrow test for it with the 6 steps above, then add the failure cases.
When a UI-facing integration fails, ScreenSnap Pro keeps region capture, callouts, solid-box redaction, OCR and screen recording in one app. It is a one-time $34 purchase: 1 license, 2 seats (2 computers, Mac or Windows). See pricing.
Morgan
Indie DeveloperIndie developer, founder of ScreenSnap Pro. A decade of shipping consumer Mac apps and developer tools. Read full bio
@m_0_r_g_a_n_

