Chapter 4. Interaction testing using mock objects

 

This chapter covers

  • Defining interaction testing
  • Understanding mock objects
  • Differentiating fakes, mocks, and stubs
  • Exploring mock object best practices

In the previous chapter, you solved the problem of testing code that depends on other objects to run correctly. You used stubs to make sure that the code under test received all the inputs it needed so that you could test its logic independently.

Also, so far, you’ve only written tests that work against the first two of the three types of end results a unit of work can have: returning a value and changing the state of the system.

In this chapter, we’ll look at how you test the third type of end result—a call to a third-party object. You’ll check 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 that aren’t under your control or aren’t part of the unit of work under test. Using the approach you’ve employed so far won’t do here, because there’s no externalized API that you 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? You use mock objects.

The first thing we need to do is define interaction testing and how it’s different from the testing you’ve done so far—value-based and state-based testing.

4.1. Value-based vs. state-based vs. interaction testing

4.2. The difference between mocks and stubs

4.3. A simple handwritten mock example

4.4. Using a mock and a stub together

4.5. One mock per test

4.6. Fake chains: stubs that produce mocks or other stubs

4.7. The problems with handwritten mocks and stubs

4.8. Summary

sitemap