What is a unit test, and how does it differ from an integration test?
Quick Answer
A unit test verifies one small piece of logic (a method/class) in isolation, with dependencies replaced by test doubles — fast, deterministic, no I/O. An integration test verifies that several components work together, often hitting a real database, HTTP endpoint or file system — slower and broader.
A unit test checks one small unit of behaviour — usually a single method or class — completely on its own, with all the dependencies faked, so it runs in milliseconds and always gives the same result. An integration test checks that pieces actually work together — a repository against a real database, a controller through the real pipeline — so it's slower but it catches the mapping and configuration bugs a unit test can't see. The test pyramid says have lots of the fast unit tests, a moderate number of integration tests, and only a handful of full end-to-end ones.
- The test pyramid: lots of unit tests, fewer integration tests, very few end-to-end tests — because cost and flakiness increase as you go up.
- Unit tests give fast feedback and pinpoint failures; integration tests catch wiring, mapping, SQL and configuration bugs unit tests can't.
- A unit test that touches the database or the network is really an integration test — and it's slow and brittle.
- Dependency injection is what makes unit testing possible: you inject fakes for the real collaborators.