Chapter 5. Mocks and test fragility

 

This chapter covers

  • Differentiating mocks from stubs
  • Defining observable behavior and implementation details
  • Understanding the relationship between mocks and test fragility
  • Using mocks without compromising resistance to refactoring

Chapter 4 introduced a frame of reference that you can use to analyze specific tests and unit testing approaches. In this chapter, you’ll see that frame of reference in action; we’ll use it to dissect the topic of mocks.

The use of mocks in tests is a controversial subject. Some people argue that mocks are a great tool and apply them in most of their tests. Others claim that mocks lead to test fragility and try not to use them at all. As the saying goes, the truth lies somewhere in between. In this chapter, I’ll show that, indeed, mocks often result in fragile tests—tests that lack the metric of resistance to refactoring. But there are still cases where mocking is applicable and even preferable.

This chapter draws heavily on the discussion about the London versus classical schools of unit testing from chapter 2. In short, the disagreement between the schools stems from their views on the test isolation issue. The London school advocates isolating pieces of code under test from each other and using test doubles for all but immutable dependencies to perform such isolation.

5.1. Differentiating mocks from stubs

5.2. Observable behavior vs. implementation details

5.3. The relationship between mocks and test fragility

5.4. The classical vs. London schools of unit testing, revisited

Summary

sitemap