Unit tests with mocks prove that each piece does what it should when its collaborators behave as expected. Many real defects live exactly where that assumption breaks: a query that's valid in your head but not in the database, a constraint nobody remembered, a transaction that doesn't roll back, an API whose response changed shape. Integration tests run your code against real dependencies to catch them. This lesson covers what to integrate, how to keep integration tests isolated and repeatable, testing databases, HTTP APIs, and external services, and contract testing between teams, with real failing-then-passing examples in PHP and Rust.
Before you start
You should know test doubles from Unit Testing in Real Applications: Mocks, Stubs, Fixtures, and Code Coverage, basic SQL, and how an HTTP API works. Docker is helpful for running real databases in tests.
What to integrate
An integration test checks one connection that unit tests can't. Typical targets:
- Your code and its database: queries, migrations, constraints, transactions, indexes that enforce uniqueness.
- Your API and its clients: routing, validation, serialization, status codes, authentication.
- Your code and external services: payment providers, email, storage, through their real protocols, against a local stand-in or a sandbox.
- Modules owned by different people or teams, where assumptions drift.
Keep the scope narrow: an integration test should involve the components needed for one interaction, not the whole system (that's system and E2E testing, lesson 8).
Testing against a real database
Mocking the database in a test about database behavior proves nothing. Here's a PHP class that books seats. It has a defect that no mock would reveal:
<?php
declare(strict_types=1);
final class Seats
{
public function __construct(private PDO $db) {}
/** Books $count seats for a class; returns false when not enough seats are left. */
public function book(int $classId, string $email, int $count): bool
{
$update = $this->db->prepare('UPDATE classes SET seats_left = seats_left - ? WHERE id = ? AND seats_left >= ?');
$update->execute([$count, $classId, $count]);
if ($update->rowCount() === 0) {
return false;
}
$insert = $this->db->prepare('INSERT INTO bookings (class_id, email, seats) VALUES (?, ?, ?)');
$insert->execute([$classId, $email, $count]);
return true;
}
}The PHPUnit test uses a real database engine (SQLite in memory, created fresh for every test) with the same constraints as production, including "one booking per person per class":
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../src/Seats.php';
final class SeatsTest extends TestCase
{
private PDO $db;
protected function setUp(): void
{
// A real database engine, in memory: fresh for every test.
$this->db = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$this->db->exec('CREATE TABLE classes (id INTEGER PRIMARY KEY, seats_left INTEGER NOT NULL)');
$this->db->exec('CREATE TABLE bookings (id INTEGER PRIMARY KEY, class_id INTEGER NOT NULL, email TEXT NOT NULL, seats INTEGER NOT NULL, UNIQUE (class_id, email))');
$this->db->exec('INSERT INTO classes (id, seats_left) VALUES (1, 5)');
}
private function seatsLeft(): int
{
return (int) $this->db->query('SELECT seats_left FROM classes WHERE id = 1')->fetchColumn();
}
public function testBooksSeatsAndCountsThemDown(): void
{
$this->assertTrue((new Seats($this->db))->book(1, 'ada@example.test', 2));
$this->assertSame(3, $this->seatsLeft());
}
public function testADuplicateBookingKeepsTheSeatCountCorrect(): void
{
$seats = new Seats($this->db);
$seats->book(1, 'ada@example.test', 2);
try {
$seats->book(1, 'ada@example.test', 1); // the same person again: the UNIQUE constraint refuses it
$this->fail('Expected the duplicate booking to be refused');
} catch (PDOException) {
}
$this->assertSame(3, $this->seatsLeft());
}
}Running it with PHPUnit 12:
PHPUnit 12.5.42 by Sebastian Bergmann and contributors.
..F 3 / 3 (100%)
There was 1 failure:
1) SeatsTest::testADuplicateBookingKeepsTheSeatCountCorrect
Failed asserting that 2 is identical to 3.
FAILURES!
Tests: 3, Assertions: 5, Failures: 1.What went wrong
The duplicate booking was correctly refused by the database, but only after the seat count had already been decreased. One seat vanished: the class now shows 2 free seats while only 2 of 5 are booked. In production, that's a class that sells out while seats are empty, and nobody can tell why.
The cause is that two related writes aren't atomic. The fix is a transaction: both writes happen, or neither does.
public function book(int $classId, string $email, int $count): bool
{
$this->db->beginTransaction();
try {
$update = $this->db->prepare('UPDATE classes SET seats_left = seats_left - ? WHERE id = ? AND seats_left >= ?');
$update->execute([$count, $classId, $count]);
if ($update->rowCount() === 0) {
$this->db->rollBack();
return false;
}
$insert = $this->db->prepare('INSERT INTO bookings (class_id, email, seats) VALUES (?, ?, ?)');
$insert->execute([$classId, $email, $count]);
$this->db->commit();
return true;
} catch (Throwable $error) {
$this->db->rollBack();
throw $error;
}
}OK (3 tests, 5 assertions)A unit test with a mocked database would have passed both versions, because the mock knows nothing about the UNIQUE constraint. Only the real engine reveals the bug.
Use the same database engine as production
SQLite in memory is fast and convenient, but it isn't PostgreSQL or MySQL: types, locking, constraint behavior, and SQL dialects differ. For anything engine-specific, run the real engine in a container:
docker run --rm -d --name test-db -e POSTGRES_PASSWORD=test -p 5433:5432 postgres:17Tools such as Testcontainers (available for TypeScript, Rust, PHP, Java, and others) start a container from test code and remove it afterwards. Laravel's RefreshDatabase trait and Rails-style transactional tests take care of resetting the schema and data between tests.
Keeping integration tests isolated
Shared state is the enemy of reliable integration tests. Common strategies, from fastest to most thorough:
- Wrap each test in a transaction and roll it back at the end. Fast, but code that manages its own transactions or uses several connections may not fit.
- Truncate tables between tests.
- Create unique data per test (unique emails, IDs) so tests can run in parallel against one database.
- A fresh database per test file, created from a template or a migrated snapshot.
Whatever you choose, every test should set up the data it needs, and never depend on data another test created or on the order tests run in.
Integration tests in Rust
Rust treats integration tests as a first-class idea: files in the tests/ directory are compiled as separate programs that use your library through its public API only, just as other code would. A library that splits a quantity into portions had this unit test fail:
running 2 tests
tests::never_loses_grams --- FAILED
thread 'tests::never_loses_grams' panicked at src/lib.rs:20:9:
assertion `left == right` failed
left: 99
right: 100
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered outSplitting 100 grams among 3 people with integer division gave 33 each, losing a gram. After distributing the remainder, the unit tests and the integration tests in tests/portions.rs pass:
use portions::split_portions;
#[test]
fn hundred_grams_for_three() {
assert_eq!(split_portions(100, 3), vec![34, 33, 33]);
}
#[test]
#[should_panic(expected = "divide by zero")]
fn zero_people_is_a_bug_in_the_caller() {
split_portions(100, 0);
} Running unittests src/lib.rs
test tests::never_loses_grams ... ok
test tests::splits_evenly ... ok
Running tests/portions.rs
test hundred_grams_for_three ... ok
test zero_people_is_a_bug_in_the_caller - should panic ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outTesting HTTP APIs
API integration tests send real HTTP requests to your application (started in the test, often on a random port, or called in-process) and check status codes, headers, and bodies:
import request from "supertest";
import { describe, expect, it } from "vitest";
import { app } from "../src/app";
describe("POST /api/bookings", () => {
it("rejects a group larger than 8 with a clear error", async () => {
const res = await request(app).post("/api/bookings").send({ classId: "ramen-basics", people: 9 });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "Groups are 1 to 8 people" });
});
it("requires sign-in", async () => {
const res = await request(app).get("/api/bookings/mine");
expect(res.status).toBe(401);
});
});Test the cases clients depend on: validation errors, authentication and authorization (see Secure Authentication, Authorization, and Session Management), not-found responses, and the exact response shape.
External services and contracts
You don't want tests to charge real cards or depend on a provider's uptime. Options:
- The provider's sandbox (test mode), for a small number of tests that confirm the real integration still works.
- A local stand-in server that speaks the same HTTP protocol, for most tests, so you test your HTTP client code, retries, and timeouts for real.
- Contract tests when two teams own the two sides of an API. In consumer-driven contract testing (for example with Pact), the client's tests record the requests it makes and the responses it relies on; the provider's CI verifies it still satisfies that contract. Alternatively, validate requests and responses against a shared OpenAPI schema in both projects' tests.
Contract tests catch the classic integration failure: a provider renames a field, every provider test passes, and every client breaks.
Common mistakes and troubleshooting
- Mocking the database in database tests. Use a real engine, ideally the production one.
- Tests that depend on each other's data. Each test creates what it needs.
- Tests against shared staging data. Someone changes it and tests fail for no reason. Use dedicated test databases.
- Calling real third-party services in every run. Slow, flaky, and possibly costly. Use local stand-ins, with a few sandbox checks.
- No timeouts on external calls. One hanging dependency hangs the suite.
- Ignoring migrations. Run the real migrations to build the test schema, so tests catch migration mistakes too.
- "Address already in use" when starting a test server: use a random free port (port 0) instead of a fixed one.
Practical exercise: find a seam bug
- Create a small project in your language with a function that writes to two tables.
- Write an integration test against a real database (SQLite in memory, or PostgreSQL in Docker) with a constraint that can fail on the second write.
- Confirm the test fails without a transaction, then fix it with one and watch it pass.
- Add an API test for one validation error and one authorization failure.
- Make tests independent: run them in a random order (Vitest:
--sequence.shuffle; PHPUnit:--order-by=random) and confirm they still pass.
Key takeaways
- Integration tests check connections that unit tests mock away: databases, APIs, external services, and team boundaries.
- Use real engines, ideally the same one as production, often in containers.
- Isolate tests with transactions, truncation, unique data, or fresh databases; never depend on test order.
- Test APIs through real HTTP, including errors and authorization.
- Use local stand-ins and sandboxes for external services, and contract tests between teams.
References
- PHPUnit documentation (opens in a new tab)
- The Rust Book: Test Organization (integration tests) (opens in a new tab)
- Testcontainers (opens in a new tab)
- Laravel: Database testing (opens in a new tab)
- Pact: Consumer-driven contract testing (opens in a new tab)
- Martin Fowler: Integration Test (opens in a new tab)
- PHP manual: PDO transactions (opens in a new tab)
What's next
The next level up tests the whole application the way a person uses it. End-to-End Testing with Playwright: Automating Real User Workflows shows how, and why tests should see what users see.

