Unit Testing
What is it?
Unit testing checks the smallest pieces of code — like a single function — in isolation to confirm they work correctly.
Explain like I'm 5
Why was it created?
Bugs in small pieces are cheap to catch early. Unit testing was adopted to verify individual parts quickly and automatically.
Where is it used?
- Verifying functions and classes
- CI pipelines
- Preventing regressions
- Supporting refactoring
Why should developers care?
Unit tests are the foundation of most test suites, so nearly every developer writes and maintains them.
How does it work?
You write small tests that call a function with specific inputs and assert the expected output. They run fast and in isolation, often replacing external dependencies with simple fakes so only the unit under test is exercised.
Real-world example
A test calls a calculateTax() function with a known amount and asserts the exact tax it should return, failing immediately if the logic breaks.
Common use cases
- Checking individual functions
- Fast feedback during development
- Catching regressions
- Documenting expected behavior
Advantages
- Fast and cheap to run
- Pinpoints failures precisely
- Enables safe refactoring
- Acts as living documentation
Disadvantages
- Don't catch integration issues
- Can be over-mocked and misleading
- Maintenance overhead
- Coverage can give false confidence
When should you use it?
For logic-heavy functions and units where correctness matters and behavior is well-defined.
When should you avoid it?
As the only testing layer — they miss how pieces work together (use integration tests too).
Alternatives
Related terms
Interview questions
Beginner
- What is a unit test?
- Why test in isolation?
Intermediate
- What is a mock or fake?
- What makes a good unit test?
Senior
- When does heavy mocking make tests misleading?
- How do unit and integration tests complement each other?
Common misconceptions
- "High unit-test coverage means the app works" — units can pass while their integration fails.
- "Unit tests should hit the real database" — that's an integration test; unit tests isolate the unit.
Fun facts
- Unit tests are meant to run in milliseconds, so you can run thousands quickly.
- Over-mocking can make a test pass even when the real code is broken.
Timeline
- 2000s — Unit testing frameworks become standard across languages
Learning resources
Quick summary
Unit testing verifies the smallest pieces of code in isolation, giving fast, precise feedback and enabling safe refactoring.
Cheat sheet
- Test smallest units in isolation
- Fast and precise
- Enables refactoring
- Pair with integration tests