Chapter 4. Interaction testing using mock objects
This chapter covers
- Defining interaction testing
 - Understanding mock objects
 - Differentiating mocks and stubs
 - Exploring mock object best practices
 
In the previous chapter, we solved the problem of testing code that depends on other objects to run correctly. We used stubs to make sure that the code under test received all the inputs it needed so that we could test its logic independently.
In this chapter, we’ll look at how you test whether an object calls other objects correctly. The object being called may not return any result or save any state, but it has complex logic that needs to result in correct calls to other objects. Using the approach we’ve employed so far won’t do here, because there’s no externalized API that we can use to check if something has changed in the object under test. How do you test that your object interacts with other objects correctly? We’ll use mock objects.
The first thing we need to do is define what interaction testing is, and how it’s different from the testing we’ve done so far—state-based testing.
We defined state-based testing in section 2.6 of chapter 2. Let’s define interaction testing, and then look at how we use it in our unit tests.
Definition
Interaction testing is testing how an object sends input to or receives input from other objects—how that object interacts with other objects.