Ruthlessly Helpful
Stephen Ritchie's offerings of ruthlessly helpful software engineering practices.
Fakes, Stubs and Mocks
October 23, 2020
Posted by on I’m frequently asked about the difference between automated testing terms like fakes, stubs and mocks.
The term fake is a general term for an object that stands in for another object; both stubs and mocks are types of fakes. The purpose of a fake is to create an object that allows the method-under-test to be tested in isolation from its dependencies, meeting one of two objectives:
1. Stub — Prevent the dependency from obstructing the code-under-test and to respond in a way that helps it proceed through its logical steps.
2. Mock — Allow the test code to verify that the code-under-test’s interaction with the dependency is proper, valid, and expected.
Since a fake is any object that stands in for the dependency, it is how the fake is used that determines if it is a stub or mock. Mocks are used only for interaction testing. If the expectation of the test method is not about verifying interaction with the fake then the fake must be a stub.
BTW, these terms are explained very well in The Art of Unit Testing by Roy Osherove.
There’s more to learn on this topic at stackoverflow https://stackoverflow.com/questions/24413184/difference-between-mock-stub-spy-in-spock-test-framework