Chapter 2. Mocking best practices

 

Chapter 9 from Unit Testing Principles, Practices, and Patterns by Vladimir Khorikov

This chapter covers

  • Maximizing the value of mocks
  • Replacing mocks with spies
  • Mocking best practices

As you might remember from chapter 5, a mock is a test double that helps to emulate and examine interactions between the system under test and its dependencies. As you might also remember from chapter 8, mocks should only be applied to unmanaged dependencies (interactions with such dependencies are observable by external applications). Using mocks for anything else results in brittle tests (tests that lack the metric of resistance to refactoring). When it comes to mocks, adhering to this one guideline will get you about two-thirds of the way to success.

This chapter shows the remaining guidelines that will help you develop integration tests that have the greatest possible value by maxing out mocks’ resistance to refactoring and protection against regressions. I’ll first show a typical use of mocks, describe its drawbacks, and then demonstrate how you can overcome those drawbacks.

9.1. Maximizing mocks’ value

9.2. Mocking best practices

Summary