Course contentsShow
← Computer Science
Lesson 2230 of 2,87250. Software TestingFree lesson

Mocking and Test Doubles

Understand mocks, stubs, and fakes to isolate units from external dependencies.

Mocking and Test Doubles

What you'll learn: How to use test doubles—mocks, stubs, and fakes—to isolate the code you're testing from external dependencies like databases, APIs, or file systems.

Why Test Doubles Matter

When writing unit tests, you want to test one unit in isolation. But real code often depends on other systems: a function might call a database, send an email, or hit an external API. Testing with real dependencies is slow, unpredictable, and breaks the "unit" in unit testing.

Test doubles are stand-ins that replace these dependencies during tests—like stunt doubles in movies.

The Three Main Types

Stubs

A stub returns predetermined responses. You control what it gives back, ignoring how it's called.

Analogy: A cardboard cutout of a person—it looks right from the front, but does nothing.

Mocks

A mock records how it's used and lets you verify interactions: "Was this method called? With what arguments? How many times?"

Analogy: A mock witness who not only plays their role but reports back exactly what happened during the scene.

Fakes

A fake has a working implementation, but simplified. For example, an in-memory database instead of PostgreSQL.

Analogy: A practice sword—functional for training, but not the real thing.

When to Use Each

  • Stub: When you need controlled responses (e.g., "pretend the API returned this JSON")
  • Mock: When you need to verify behavior (e.g., "ensure the logger was called exactly once")
  • Fake: When you need realistic behavior without real infrastructure (e.g., in-memory cache)

Key Takeaway: Test doubles let you isolate units by replacing dependencies with controllable stand-ins—stubs provide data, mocks verify calls, and fakes offer lightweight implementations.