Unit Testing
Testing individual components or functions in isolation to verify they work correctly, forming the foundation of a testing strategy.
Detailed Explanation
Unit tests verify that individual units of code (functions, methods, classes) work correctly in isolation. They are fast (milliseconds), focused (one assertion per test), and form the base of the testing pyramid. Good unit tests catch regressions early, serve as documentation, and enable confident refactoring.
Unit tests mock external dependencies (databases, APIs, file systems) to isolate the unit under test. Popular frameworks: Jest (JavaScript), Pytest (Python), JUnit (Java), Go testing (Go), and RSpec (Ruby). Aim for high coverage of critical business logic, not 100% coverage of all code.
Why It Matters
Unit tests are the fastest, cheapest way to catch bugs. They enable refactoring, improve code design, and serve as living documentation.
Real-World Example
A developer writes a unit test for a price calculation function: `expect(calculatePrice(100, 0.2)).toBe(80)`. The test runs in 5ms and catches any regression in pricing logic.
When to Use
For all business logic, utility functions, data transformations, and algorithms. Skip unit tests for simple UI components and integration points.
Advantages
- Fast feedback (milliseconds)
- Catches regressions early
- Serves as living documentation
- Enables confident refactoring
- Forces better code design (testable code)
Disadvantages
- Does not catch integration issues
- Mocks can hide real-world behavior
- Can give false confidence
- Maintenance burden for tests
- Difficult to test asynchronous code
Related Terms
Frequently Asked Questions
What is the testing pyramid?
The testing pyramid recommends: many unit tests (fast, cheap), fewer integration tests (medium speed and cost), and few E2E tests (slow, expensive). Unit tests form the base for fast feedback.
How much test coverage do I need?
Aim for 70-80% overall, with 90%+ coverage on critical business logic. 100% coverage is rarely worth the effort. Focus on testing behavior, not implementation details.
Should I mock external dependencies?
Yes, for unit tests. Mock databases, APIs, and file systems to isolate the unit under test. Use integration tests (with real dependencies) to verify that components work together.
What is test-driven development (TDD)?
TDD is writing tests before writing code: write a failing test, write the minimum code to pass, refactor. It produces better code design and higher test coverage but requires discipline.
When should I NOT write unit tests?
Skip unit tests for: simple UI components (test with integration tests), configuration files, and code that is trivially correct. Focus unit tests on business logic and complex algorithms.