Site Tools


unit-test

Table of Contents

Unit test

A unit test is a test that verifies a single, isolated unit of code — typically a function or a class method — in isolation from its dependencies. The goal is to make the test fast, deterministic, and precise about what it is testing.

// function under test
int clamp(int value, int lo, int hi) {
    if (value < lo) return lo;
    if (value > hi) return hi;
    return value;
}
 
// unit tests
assert(clamp(5,  0, 10) == 5);   // inside range: unchanged
assert(clamp(-3, 0, 10) == 0);   // below lo: clamped to lo
assert(clamp(15, 0, 10) == 10);  // above hi: clamped to hi
assert(clamp(0,  0, 10) == 0);   // on boundary: inclusive
assert(clamp(10, 0, 10) == 10);

“Isolated” is the operative word. A unit test does not read from disk, does not open a socket, and does not call a real database. Dependencies are replaced with fakes (stubs, mocks) that return controlled values. This isolation is what makes unit tests fast (microseconds, not seconds) and deterministic (they do not flake because the database was slow).

Unit tests sit at the bottom of the test pyramid. They are cheap to write, cheap to run, and cheap to maintain, so you have many of them. Integration tests and end-to-end tests sit above: they cover more of the system but are slower and more brittle.

The main limitation of unit tests is that they cannot catch bugs that only appear when components interact. A function can have 100% unit test coverage and still fail in integration because it passes data in a format the downstream component does not expect. Unit tests and integration tests complement each other; neither replaces the other.

unit-test.txt · Last modified: by 127.0.0.1