I’ve recently noticed a number of posts criticizing mocking frameworks, where half the responses are defending the idea of mocking rather than talking about the frameworks that had been called out1. Let’s be clear that those are two completely different things.
We can agree that mocking as a concept is useful, while strongly criticizing mocking frameworks.
In general, mocking as a technique is widely overused. There are situations where it absolutely makes sense and situations where it clearly does not. When it’s really easy to create mocks then we tend to create more of them than we should, and also use them inappropriately. This is where the criticism is justified IMO. Mocking frameworks makes it really easy to do the wrong thing so we do more of the wrong thing.
Note that when I say “mocks”, I’m using that word to describe all of mocks, stubs, fakes, spies, etc. The idea is the same across all of them.
What’s an example of doing the wrong thing?
Here’s a case where a mocking framework was used to override the getter method when we could have first just called the setter. I’ve seen this one in real code.
// Using the mocking framework foolishly
Customer customer1 = mock(Customer.class);
when(customer1.getFirstName()).thenReturn("Amy");
// When we could have just used the object as it's
// already designed to be used.
Customer customer2 = new Customer();
customer2.setFirstName("Bob");
I’ve seen codebases with dozens of lines of mocking setup for each test, simply because they could. The developers gave no thought to how to decompose the application into more testable pieces because the mocking framework made it too easy to continue supporting a poor design.
You may be thinking that we shouldn’t be blaming the tool, and there is some truth to that.
Unfortunately, these are tools that encourage sloppy thinking and lazy design and that’s a real problem. We need more thinking, not less, and tools that encourage the wrong things are a problem.
Mocking is a useful technique to have in your back pocket. It’s not a technique that we should use blindly, without thinking.
-
This is an example of a psychological phenonomenon called Attribute Substitution where we are faced with a computationally difficult decision, we will often substitute a more easily calculated decision in it’s place and answer that instead, without even realizing that we did this. ↩