Discussion: The problem of mocking and pros/cons of Midje - Baldridge, Corfield, Marick
In the discussion How to handle refactoring with TDD and mocking/stubbing, Timothy Baldridge writes:
I don't recommend Midje at all. Many of the framework's mocking facilities (such as providing) are abominations. You shouldn't go around mucking with functions and re-deffing them on the fly. It may look cute, but I've lost countless hours to bugs and unexpected behavior related to Midje. IMO, stay clear of that. The pattern I do recommend is to break your system up into components. Each component should be testable by mocking its dependencies and then testing only that component. In a final test, stitch together all your components and run system tests against all components at once. If you do what Ashton suggests and use temporary databases, this will work quite well. This way you get the detailed errors of unit tests when things fail inside a component, as well as contractual tests between components. I highly recommend Stuart Sierra's Component Library for all of this: https://github.com/stuartsierra/component It forces you to define the dependencies of each component, and so mocking or stubbing out a component is almost trivial.
Your mileage, experience and needs may differ, but it is worth listening to Tim's opinion as he is a visible figure in the Clojure world and a Cognitect employee. Personally I like Midje but I absolutely agree that mocking is mostly an anti-pattern. Splitting code in components and testing those as units (instead of individual functions) while stubbing/mocking their dependencies makes good sense. (Though sometimes I really like to test individual functions - even if I discard the tests afterwards.)
Sean Corfield, another Clojure giant :-), agrees:
I agree with Timothy here: we have about 6kloc test code (for a production code base of about 24kloc) and only have 25 with-redefs to stub just 8 functions in our Expectations code. In addition we use Expectations’ side-effects to mock just one function in four tests. Whenever we find ourselves needing to stub or mock in tests, we usually try to refactor the code so it’s easier to test fully without that.
The ensuing discussion between Brian and Tim is worthy reading. There are good opinions on both sides.








