Skip to content
Alphabin

A Mock Object is a test double that imitates a real dependency, such as a database, an external API or a payment gateway. It returns controlled responses and records how it was called, so a test can check the code under test in isolation and verify that it interacts with the dependency correctly.

Key components of using mock objects include:

  • Isolation: Replacing slow, unreliable or costly dependencies keeps unit tests fast and focused on one piece of code.
  • Controlled Behavior: A mock can be set up to return specific data, raise errors or time out, making hard-to-trigger scenarios easy to test.
  • Interaction Verification: Tests can assert that a method was called, how many times, and with which arguments.
  • Related Test Doubles: Stubs return fixed answers, fakes provide lightweight working implementations, and spies record calls on a real object.

Mocks make unit tests reliable, but overusing them can tie tests to implementation details and hide problems that only appear when real components work together, which is why integration tests remain important.