Skip to content

Testing in Isolation

Question

How can you unit test in isolation?

Short interview answer

Design the unit around explicit dependencies, pass controlled test doubles for external collaborators, and keep time, I/O, and random inputs deterministic. Assert observable results or interactions that are part of the unit’s contract.

Detailed answer

Start by separating business logic from infrastructure through constructor parameters or other explicit dependencies. For example, a service that needs the current time can depend on an interface whose test implementation always returns 2026-08-29T10:00:00Z; the production implementation can read the real clock. Use fakes, stubs, or mocks only at boundaries such as a database, file system, HTTP client, clock, or message publisher. Do not mock every class: a test that only checks a chain of mocks can pass even when the real behavior is wrong. A good isolated test stays fast, repeatable, self-checking, and focused on one behavior.

Sources