Integration vs Unit Tests: What Each One Catches
Unit tests isolate one piece; integration tests verify pieces work together. Learn the trade-offs and how to balance the two.
By Velloreth
The distinction
A unit test isolates one piece of code. Dependencies are replaced with fakes or stubs, so the test exercises only the code under test.
An integration test exercises several pieces together, with real dependencies. It verifies that the components work in combination.
// Unit test: the repository is a fake
test('creates a user', async () => {
const repo = new InMemoryUserRepository();
const service = new UserService(repo);
await service.createUser({ email: 'ada@example.com' });
expect(await repo.findByEmail('ada@example.com')).not.toBeNull();
});
// Integration test: the repository is real, backed by a database
test('creates a user in the database', async () => {
const db = await createTestDatabase();
const repo = new PostgresUserRepository(db);
const service = new UserService(repo);
await service.createUser({ email: 'ada@example.com' });
const row = await db.query('SELECT * FROM users WHERE email = $1', ['ada@example.com']);
expect(row.rows).toHaveLength(1);
});
The second test runs the real SQL against a real schema. If the query has a syntax error, or the column name is wrong, this test catches it. The unit test cannot.
What each catches
| Bug type | Unit | Integration |
|---|---|---|
| Logic error in a function | Yes | Yes |
| Off-by-one | Yes | Yes |
| Wrong SQL column | No | Yes |
| Missing migration | No | Yes |
| Serialisation mismatch | No | Yes |
| Wrong config key | No | Yes |
| Wiring error | No | Yes |
| Transaction issue | No | Yes |
| Concurrency bug | Rarely | Sometimes |
| UI layout | No | No |
The pattern is clear. Unit tests catch logic errors inside a component. Integration tests catch errors at the seams between components.
The bugs only integration tests find
Schema mismatches. The code expects user_id; the column is userId. The unit test passes because the fake accepts anything.
Serialisation problems. A date is serialised as a string but deserialised as a number. The unit test never crosses the boundary.
Configuration errors. The environment variable is named DATABASE_URL in the code and DB_URL in the deployment. Only a test that reads real configuration catches it.
Transaction and isolation issues. A write is not committed, or a read happens before a write is visible. These require a real database.
Wiring errors. A dependency is not registered, or the wrong implementation is injected. The unit test constructs the object graph manually, so it never sees the real wiring.
Mismatched assumptions. Service A sends a field that service B ignores. Each is correct in isolation; together they lose data.
These are the bugs that reach production when a team relies only on unit tests. They are also the bugs that are hardest to debug, because each component looks correct.
The trade-offs
Speed. A unit test runs in milliseconds. An integration test with a database takes tens or hundreds of milliseconds. A suite of 1,000 integration tests takes minutes.
Isolation. A unit test failure points at one function. An integration test failure could be in any of the components involved, which makes diagnosis harder.
Setup cost. Integration tests need a database, a container, migrations, and cleanup. That is real infrastructure to maintain.
Confidence. Integration tests give more confidence per test, because they exercise more of the system.
Flakiness. Integration tests are more prone to flakiness — network timeouts, port conflicts, leftover state. Unit tests are deterministic.
The test pyramid
The standard model balances the trade-offs.
/\
/ \ End-to-end (few, slow, high confidence)
/----\
/ \ Integration (moderate, medium speed)
/--------\
/ \ Unit (many, fast, pinpoint failures)
/------------\
Many unit tests. Fast, cheap, and they pinpoint failures. They cover the logic thoroughly.
Fewer integration tests. They cover the main flows and the boundaries between components.
A few end-to-end tests. They exercise the whole system through the UI or the public API, verifying the critical paths work.
The shape is a pyramid because the cost increases as you go up. You want most of your tests at the cheap end.
The testing trophy
An alternative model, popular in the JavaScript community, inverts the emphasis.
/\
/ \ End-to-end (few)
/----\
/ \ Integration (most)
\ /
\----/
\ / Unit (some)
\/
The argument is that integration tests give the best confidence per unit of effort, because they catch both logic and wiring errors. Unit tests are reserved for complex logic that is hard to exercise through integration.
The right model depends on your system. A system with complex business logic benefits from many unit tests. A system that is mostly wiring — a CRUD API, a data pipeline — benefits from more integration tests.
Practical guidance
Write unit tests for:
- Complex business rules.
- Algorithms and calculations.
- Parsers and formatters.
- Edge cases and boundary conditions.
- Pure functions.
Write integration tests for:
- Database queries and migrations.
- API endpoints.
- Message queue producers and consumers.
- External service clients.
- Configuration loading.
- The main user flows.
Write end-to-end tests for:
- The critical paths — signup, login, checkout.
- Smoke tests after deployment.
Making integration tests work
Use containers. Docker Compose or Testcontainers gives you a real database, started and torn down per run.
Reset state between tests. Truncate tables or wrap each test in a transaction that rolls back.
Run them separately. Keep integration tests in a separate suite so the fast unit tests can run on every save.
Parallelise carefully. Integration tests often share resources, so parallel execution needs isolated databases or schemas.
Accept the cost. Integration tests are slower. That is the price of the confidence they provide.
Practical guidance
- Write many unit tests for logic, and fewer integration tests for wiring.
- Use a real database in integration tests — mocking it defeats the purpose.
- Reset state between tests so they are independent.
- Run integration tests separately from the fast unit suite.
- Cover the main flows with integration tests, not every branch.
- Keep a few end-to-end tests for the critical paths.
- Do not chase 100% coverage in either category — cover what matters.
For the related practices, see unit testing basics and mocking and stubbing. For the broader context, test-driven development guide and why your tests are slow.
Quotable summary
A unit test isolates one piece of code with dependencies replaced by fakes, while an integration test exercises several components together with real dependencies. Unit tests are fast and pinpoint failures; integration tests are slower but catch wiring errors, SQL and schema mismatches, serialisation problems, configuration mistakes, and transaction issues that unit tests cannot see. Neither replaces the other, because unit tests miss integration bugs and integration tests are too slow to cover every branch. The test pyramid balances them with many unit tests, fewer integration tests, and a small number of end-to-end tests, and the right balance depends on whether your system is mostly logic or mostly wiring.