Field Guide · concept

Mocking is the use of test doubles — stand-ins for a unit’s real dependencies — so the unit can be tested in isolation, deterministically and without touching real networks, databases, or hardware.1

code undertest calls test doublemock / fake / stub real DB /radio (skipped)
A test double replaces the real dependency so the unit runs fast and deterministically.

Kinds of test double

“Mocking” is the everyday umbrella term, but there are distinct kinds of double:

  • Fake — a lightweight working implementation, for example a sample source that replays a file instead of reading a live device.
  • Stub — simply returns canned, pre-programmed responses, with no logic of its own.
  • Mock — records how it was called and lets the test assert that the code interacted with it correctly (it called send() once, with these arguments).1

The right double depends on what you’re testing: a stub or fake when you only need the dependency to be present, a mock when the interaction itself is the behavior under test.

Why it works

Mocking depends on the dependency inversion idea: if your code talks to an interface rather than a concrete class, a test can inject a double in place of the real thing. That is what makes unit tests fast and deterministic — no flaky network, no slow database, no hardware in the loop. Good seams make code mockable, and mockable code tends to be well-designed code, which is why mocking pairs so naturally with test-driven development.

When not to mock

Doubles have a cost: a test that mocks everything verifies your code against your assumptions about a dependency, not the real one. That is exactly the gap integration tests and end-to-end tests fill by using real collaborators. Over- mocking also inflates code coverage without real assurance. Mock at the boundaries of slow or external systems; let higher layers, run in CI/CD, exercise the real seams.

Sources

  1. Mock object — Wikipedia, for test doubles (mocks, fakes, stubs) and how they isolate a unit.  2

See also