One of the common uses for mocks is to replace expensive or stateful components, such as file systems, networks, GUIs, and databases.
However, I also see a cluster of other problems that arise at interfaces with these types of components, especially when they are system-level services:
- Primitive obsession. Rarely are these APIs written as methods on an abstract object that return other abstractions. Instead, people pass around a lot of strings & things, which become arguments for static methods.
- State. Partly because there isn’t a place to put it, state tracking becomes a mess. For example, you want to ask a web service for something. Are you logged in? Do you have to do something if you aren’t?
- Lack of encapsulation. Those static methods end up everywhere. And often they end up with duplicate patterns everywhere (e.g., check for login before each call).
- The API does not feel natural to the application. It doesn’t follow the project’s idioms, and doesn’t just flow into place.
For this reason, I use an entirely different sort of test double: a system simulator. And often these simulators stop being test doubles Continue reading “Mock Free Example, part 2: Simulators”