A new consulting gig I just started last week has a team who is interested in diving deep into Mock Objects as a testing philosophy. As such, I’ve spent some time reacquainting myself with Mocking after having passed on it several years ago.
My chief complaint, as the doctors say, was that Mocking introduced an unnecessary level of complexity to your testing code. My secondary complaint was that it broke encapsulation by giving your test code too much insight as to the expected implementation of your classes, what with all the .expect()s and .will()s floating around. It’s like washing the family car with your Dad hovering over your shoulder, telling you the right way to use the sponge. As long as it’s clean at the end, who cares?
In a nutshell, this is the argument over state-based vs. behavioral testing. In state-based testing, you just want Car.IsClean() to return true. In behavioral testing, you want Sponge.Wipe() to be called 137 times, and Hose.Spray() to be called 22 times.
Call me a keen proponent of state-based testing.
There are a couple areas where Mocking can get around very real weaknesses in state-based testing; for example, anything to do with nondeterministic behavior. The authors of this paper, “Mock Roles, Not Objects”, conveniently use caching as a way to explore Mocking, and it make sense. It would be hard to test caching to that level of detail without either (a) Mocks or (b) exposing a lot of guts of the implementation just to hang test hooks off of.
What’s your experience with Mocking? Any best practices to relate?








