Skip to main content

Mocking

Mocking replaces real dependencies with controllable stand-ins so tests can isolate the code under test, run fast, and verify interactions, but over-mocking causes brittle tests.

Mocking is the practice of substituting a real dependency in a test with a fake, programmable object known as a mock (or more loosely, a test double). The mock stands in for something the code under test depends on — a database, an HTTP client, a payment gateway — so the test can run in isolation, deterministically, and fast.

How It Works

A test double can take several forms. A stub returns canned responses to calls. A mock additionally records and verifies that it was called in the expected way, with the expected arguments. A fake is a lightweight working implementation, like an in-memory database. Mocking frameworks let you configure a double to return specific values, throw errors, or assert that a method was invoked a certain number of times. Mocking is most practical when code receives its dependencies via dependency injection, so the test can supply a double in place of the real collaborator.

Why It Matters

Mocking makes unit tests isolated and reliable. By replacing slow, nondeterministic, or external dependencies, tests run quickly and consistently, and a failure points clearly at the unit under test rather than at an unrelated service. Mocks also let you simulate hard-to-reproduce conditions, such as a network timeout or a third-party error, and verify that your code reacts correctly.

The main pitfall is over-mocking: tests that assert too much about internal interactions become brittle and can pass even when the real integration is broken. That is why mocking complements, but does not replace, integration tests against real components.

Related Terms

Mocking is central to fast unit tests and depends on dependency injection. Integration tests use real dependencies instead, and TDD frequently uses mocks to drive design.