Today at the GOOSgaggle event in London, Brian Marick gave the presentation “I Think I Finally Understand Mocks”. Marick started by saying that he was one of the reviewers of the original mock paper, and that he at that point completely misunderstood the idea and thought that the authors were reinventing test stubs. It wasn’t until four months ago, when he read Growing Object Oriented Software, that he really understood what the concept is all about. Marick said that “the point of mocks is illustrated by a photo of surgeon working on a cow. [You, the surgeon, work with a team and when] you explain what you want to do, reach out your hand and magically the tool you want appears in your hand”.
Demonstrating how he uses now mocks, Marick went through the design and implementation of a recent project with an exercise involving attendees pretending to be objects and mocks in four iterations. After that, he pointed out that he really designed the code in the test, rather than in the implementation. “This is just stenography”, said Marick pointing to the implementation.
There isn’t much more that happens in the implementation apart from what was in the test, and mocks allow us to describe the design in tests with less friction (note: this refers to the implementation of the object under test, not its dependent objects). Objects with complex dependencies require us to set up all those complicated dependencies in the test with classic TDD. This increases the clutter in the test. Using mocks allows us to avoid setting all that up in a test and describing the test (and design) more efficiently. Marick said that this benefit surprised him once he started using mocks properly. “Instead of giving the right time slice, mocks allow you to just give back a token representing a time slice,” said Marick, pointing how mocks facilitate outside-in design, “If it looks as if there is going to be some complicated work, I push the work away into a new object”.
“Doing top-down makes it much more likely that I’ll hit my destination”, said Marick, pointing out that there is no rational reason to choose top-down over bottom-up design, but from his experience the style of working with mocks leads to better design faster. “Things are flowing smoothly without a lot of friction.”, said Marick. Analysing the resulting code, Marick said that the objects ended up not doing much. He stressed out that conventional TDD makes him pile more and more code into a class or a method until it gets so big that “shame forces me to notice that these five methods are doing the same thing and pull them out. Things get big, then small, then big again”. “Mocking really encourages me to push”, said Marick, pointing out that with mocks he gets to smaller objects quicker, allowing him to “make decisions at the last responsible moments”.