The old “classicist” vs “mockist” debate
I have recently read Martin Fowler’s “Mocks aren’t stubs” article, of which a big part is about the (what he calls) “classicist” vs “mockist” approaches to testing and TDD.
In short, it comes down to this:
- The “classicist” prefers to write mini-integration tests that test a group of classes together without resorting to test doubles (mocks, stubs and the like) for most things unless to replace calls to an external system such as a database or web service.
- The “mockist” prefers to test units (mostly classes) in complete isolation, replacing collaborators with test doubles.
Which side to choose when doing TDD
I personally lean more towards the “classicist” approach for the following reasons:
- The “mockist” approach often tightly couples the implementation to the test and tends to make the test brittle: changes to the code will often mean changes to the test even if they don’t change the behaviour in the bigger picture of collaborating classes. And when that happens, the test has had no use since it was meant to confirm that a refactoring was done correctly without introducing bugs.
- One of the main goals of writing automated tests is to catch bugs. My experience tells me that bugs usually occur when different parts are put together and would often not get caught by testing the parts in isolation.
- Another goal is to provide documentation. Indeed, by looking at test code, it should be clear what the expected result of a piece of code is, i.e. what business value it provides. It does not have to be clear what collaborators are called in what order: that should be clear when looking at the code under test.
The first one, the tight coupling, is the most important to me. In my opinion, while refactoring it often degrades the red bar in the test report to nothing more than a glorified “Are you sure?” type popup message. And the answer would be “No, I’m not”, since I wasn’t expecting the test to be failing since my refactoring should not have any effect on the end result.
In this recent talk by Ian Cooper called “TDD, where did it all go wrong”, he explains very well why this coupling is so bad and how it is against the original spirit of TDD, as designed by Kent Beck.