Using mocks to verify interactions
In this section, we’ll take a look at another important kind of test double: the mock object. Mock objects solve a slightly different problem than stub objects do, as we shall see in this section.
Mock objects are a kind of test double that record interactions. Unlike stubs, which supply well-known objects to the SUT, a mock will simply record interactions that the SUT has with the mock. It is the perfect tool to answer the question, “Did the SUT call the method correctly?” This solves the problem of push model interactions between the SUT and its collaborator. The SUT commands the collaborator to do something rather than requesting something from it. A mock provides a way to verify that it issued that command, along with any necessary parameters.
The following UML object diagram shows the general arrangement:
Figure 8.2 – Replace collaborator with mock
We see our test code wiring up...