A mock object is a fake stand-in for a real dependency, used in a test so that a single unit of code can be exercised without its real collaborators. Instead of talking to a live database, network service, or other slow and unpredictable component, the code under test talks to the mock, which is set up specifically for the test.
The technique was introduced in the 2000 paper “Endo-Testing: Unit Testing with Mock Objects” by Tim Mackinnon, Steve Freeman, and Philip Craig. They proposed replacing real domain code with “dummy” implementations that the test controls, so that everything, including code that depends on awkward external resources, becomes unit-testable.
What distinguishes a mock from a simpler fake is that it carries expectations. Martin Fowler, in “Mocks Aren’t Stubs,” defines mocks as “objects pre-programmed with expectations which form a specification of the calls they are expected to receive.” A stub merely returns canned answers; a mock also checks that it was called in the way the test demanded.
This leads to two styles of checking. As Fowler puts it, “only mocks insist upon behavior verification,” while other test doubles “use state verification.” State verification looks at the final state of objects after the test; behavior verification, enabled by mocks, confirms that the unit made the correct calls to its collaborators during execution.