Integration Testing — Explained with Examples
Integration testing verifies that different modules or services work together correctly, catching interface mismatches and data flow issues between components.
Integration testing sits between unit testing (isolated components) and end-to-end testing (full system). It tests how components interact — for example, how the user service communicates with the database, or how the API layer calls the business logic layer.
Integration vs Unit Testing
| Aspect | Unit Test | Integration Test |
|---|---|---|
| Scope | Single function/class | Multiple components |
| Dependencies | Mocked/stubbed | Real or test doubles |
| Speed | Milliseconds | Seconds |
| Failure cause | Logic bug | Interface mismatch, config error |
Example: Testing a Database Repository
const db = require('./database');
describe('UserRepository Integration Tests', () => {
beforeAll(async () => {
await db.migrate(); // Set up real test database
await db.seed(); // Insert test data
});
afterAll(async () => {
await db.cleanup(); // Remove test data
});
test('creates and retrieves a user', async () => {
const user = await db.users.create({
name: 'Alice',
email: 'alice@test.com'
});
const found = await db.users.findById(user.id);
expect(found.name).toBe('Alice');
expect(found.email).toBe('alice@test.com');
});
test('enforces unique email constraint', async () => {
await db.users.create({
name: 'Bob',
email: 'bob@test.com'
});
await expect(
db.users.create({ name: 'Bob2', email: 'bob@test.com' })
).rejects.toThrow('Unique constraint violated');
});
});Real-World Analogy
Unit testing is checking that each pipe joint seals when tested individually. Integration testing is connecting all the pipes and turning on the water. The joints might seal individually, but the overall system could leak at connection points between different types of pipes, or the water pressure might be wrong for the pipe material.
Related Terms
Unit Testing, E2E Testing, Mock vs Stub, Smoke Testing, Regression Testing
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro