Unit Testing
Definition
Unit Testing is the first level of software testing, where individual units/modules (a function, method, or class) are tested in isolation to verify they work correctly on their own, before being integrated with other units.
Who Performs It
Typically performed by developers themselves, often immediately after writing the code (or even before, in Test-Driven Development).
Characteristics
- Smallest testable unit of the application
- Tests are usually automated (using frameworks)
- Fast to run — designed to be executed frequently (every code change)
- Focuses on internal logic correctness of a single module
Techniques Used
- Often uses white-box techniques: Path Testing, Data Flow Testing, Statement/Branch Coverage
- Can also use black-box techniques (BVA, ECP) if testing based on the unit's specification
Handling Dependencies: Stubs and Drivers
Since a unit rarely works completely alone, testers use:
- Driver — a piece of code that calls the unit under test, simulating the calling module (used when the unit's caller doesn't exist yet)
- Stub — a piece of code that simulates a module called by the unit under test, returning fake/canned responses (used when a dependency doesn't exist yet or is external)
[Driver] ──calls──▶ [Unit Under Test] ──calls──▶ [Stub(s)]
Common Unit Testing Frameworks
- JUnit (Java), pytest/unittest (Python), Jest/Mocha (JavaScript), NUnit (.NET)
Advantages
- Catches bugs early, when they're cheapest to fix
- Provides a safety net for future changes (regression protection)
- Encourages modular, testable code design
- Fast feedback loop for developers
Disadvantages
- Doesn't catch integration issues between modules (covered by Integration Testing)
- Requires investment in writing and maintaining test code
- Can give false confidence if units are tested but their interactions aren't
Exam tip: Know the Stub vs. Driver distinction clearly — Stub simulates a called module (below), Driver simulates the caller (above) — a very commonly asked short-answer/diagram question.