
ALT The term “mock” is often loosely used to mean any kind of test fake, but strictly speaking a mock is a fake that has pre‐programmed expectations about how it’s to be used, and verifies those expectations when used in a test. Mocks can become very complex and sophisticated in their behaviour, sometimes almost as complex as the real component they’re replacing. And that’s a bad thing, at least if we want to build simple, reliable tests. How do you know that your mock accurately replicates the behaviour of the real system? If it doesn’t, you’re testing the wrong thing. And there’s another problem with mocking in tests. Because a mock is programmed to expect a specific sequence of calls and parameters, it’s very tightly coupled to the way the system uses the real component. It observes the indirect outputs of the system, not its direct outputs. We’re no longer testing just the user‐visible behaviour of the system, we’re testing its implementation, which makes our tests brittle.

ALT In other words, mocking presupposes your design, rather than letting the right design gradually emerge from the desired behaviour of the system. It’s also a lot of work building all that mock code, and keeping it up to the date with the behaviour of the real component over the life of the project. It’s not that mocking is a bad idea in itself; mocks can be useful sometimes. It’s just that if you find you can’t test your system adequately without mocks, this is probably a hint that you should redesign the system instead. And building a mock certainly shouldn’t be our default approach. We should only resort to it once all the other options described in this chapter have been exhausted.




























