Unit testing checks a single small piece of code — one function or class — in isolation, forming the fast, numerous base of the test pyramid.1
What it is
A unit test exercises the smallest meaningful piece of behavior on its own, asserting that for a given input the unit produces the expected output. Because each test targets one unit, a failure points straight at the broken code.1 Unit tests are fast — a good suite runs thousands in seconds — and that speed is what lets a developer run them constantly and lets CI/CD run them on every push. They are also the safety net that makes refactoring safe: restructure freely, and a red test catches any accidental behavior change instantly.
Isolation
The “unit” in unit testing means the piece is tested in isolation from its collaborators — no real network, database, or hardware in the loop. Standing in for those dependencies is the job of mocking and other test doubles (fakes and stubs). This is where the dependency inversion idea pays off: if your code depends on an interface rather than a concrete dependency, a test can inject a fake and run deterministically. Good seams make code testable, and testable code tends to be well-designed code.
In the bigger picture
Unit tests sit at the base of the pyramid beneath fewer integration tests and a thin layer of end-to-end tests. They are the kind of test test-driven development writes first, and the kind code coverage most directly measures — though coverage shows only which lines ran, not whether the assertions checked anything meaningful.
Sources
-
Unit testing — Wikipedia, for the definition, isolation, and the test-pyramid context. ↩ ↩2