Skip to main content
Test Automation

Mocking (Test Doubles)

Using fake objects to simulate dependencies in tests, isolating the code under test.

Full definition

Mocking is the practice of replacing real dependencies with fake implementations in tests. Test doubles allow you to test code in isolation without needing real databases, APIs, or services.

Types of test doubles:

  • Mock: Records interactions — you can assert it was called with specific arguments
  • Stub: Returns predetermined values — provides canned responses
  • Fake: Working implementation with shortcuts (e.g., in-memory database)
  • Spy: Wraps the real object and records calls while passing through to real implementation
  • Dummy: Passed around but never used — fills parameter requirements

When to mock:

  • External APIs (payment gateways, email services)
  • Databases (for unit tests)
  • Time/dates (for deterministic tests)
  • File system operations

When NOT to mock:

  • Don't mock what you don't own (wrap it first)
  • Don't mock everything (integration tests should use real dependencies)
  • Don't mock the thing you're testing

Popular mocking libraries: Jest (built-in), Sinon.js, Mockito (Java), unittest.mock (Python)

Learn more about mocking (test doubles) in practice

Automation track