Skip to content

What it is

A unit test exercises one unit of production code in isolation: a pure function, a method on a class, a single service with its collaborators replaced. It runs in milliseconds, has no I/O, and asserts on the observable result of the call.

The unit is the smallest testable piece of behaviour the developer controls: a function that takes input and returns output, a method that mutates state the test can inspect, a class whose public surface can be exercised without booting the database, the queue or the network. Everything outside the unit is replaced by test doubles — stubs, fakes, mocks (see test-double, stub, fake).

Michael Feathers' definition in Working Effectively with Legacy Code (2004) is the industry's working baseline: "A test is not a unit test if it talks to a database, it communicates across the network, it touches the file system, or it can't run at the same time as any of your other unit tests." The line is not perfect — some definitions accept an in-memory database as a unit-test substitute — but the intent is clear: a unit test should be fast, deterministic and isolated.