Unit test kiểm tra một function/class cô lập với mọi dependency được mock; integration test kiểm tra tương tác giữa nhiều thành phần với dependency thật hoặc mock tối thiểu.
- Unit — nhanh (<1ms), ổn định, dễ xác định vị trí lỗi, không cần external service. Phù hợp: thuật toán, business logic, pure functions, utilities.
- Integration — chậm hơn (100ms–1s) nhưng bắt lỗi ở boundary (schema mismatch, query sai, vi phạm API contract) mà unit test không thể. Ví dụ: test API handler với database thật.
- Supertest (Node.js) —
await request(app).get('/api/users').expect(200)— test Express route với middleware stack thật, chỉ mock external services. - Test containers — spin up PostgreSQL/Redis thật trong Docker cho test: deterministic, isolated, cleanup sau khi chạy.
- Mock DB vs real DB — mock nhanh hơn nhưng có thể bỏ sót lỗi SQL syntax, constraint violation, vấn đề query performance; DB thật bắt nhiều bug thực tế hơn.
Trong microservices, contract tests thay integration tests khi services thuộc các team khác nhau. Triết lý Testing Library: 'The more your tests resemble the way your software is used, the more confidence they can give you' — integration test thường cho nhiều confidence trên mỗi test hơn unit test.