13.4 Imitating objects using mocks
Isolated problems are easier to diagnose and solve. Figuring out why a gasoline car won’t start can be tricky because there are so many interrelated parts. If a test fails, uncovering all the interrelationships among software components makes diagnosis of the problem difficult. We often want to isolate items by providing simplified imitations. It turns out there are two reasons to replace perfectly good code with imitation (or “mock”) objects:
-
The most common case is to isolate a unit under test. We want to create collaborating classes and functions so we can test one unknown component in an environment of known, trusted test fixtures.
-
Sometimes, we want to test code that requires an object that is either expensive or risky to use. Things such as shared databases, filesystems, and cloud infrastructures can be very expensive to set up and tear down for testing.
...