What are unit, integration and end-to-end tests?
Model answer
They test the system at three scales, trading speed and isolation for realism.
Unit tests check one small piece, such as a function or class, in isolation. Dependencies are replaced with fakes or mocks. They are very fast, precise about where a failure is, and stable, so you can have thousands.
Integration tests check that several components work together, for example a service with its real database, or two services over their API contract. They find wiring, configuration and query problems that unit tests cannot see. They are slower and need more setup.
End-to-end (E2E) tests drive the whole system through the user interface or public API, as a user would, such as logging in and placing an order. They give the most confidence that real flows work, but are the slowest, the most brittle and the hardest to debug.
The test pyramid suggests many unit tests, fewer integration tests and a small number of E2E tests for critical journeys. Pick the lowest level that can catch the bug.
Key points
- Unit: one piece in isolation; fast and precise
- Integration: components together, such as a service with its database
- E2E: full user flow; most realistic but slow and brittle
- Test pyramid: many unit, fewer integration, few E2E
Likely follow-ups
- What is the difference between a mock and a stub?
- Which flows deserve an E2E test?
Common mistakes
- Writing mostly E2E tests and ending up with a slow, flaky suite
- Mocking so much in unit tests that they only test the mocks