4.5.1 To Mock or not to Mock
Course subject(s)
Module 4: Testability and Mock Objects
To mock or not mock has been a big discussion among different practitioners. A few years ago, Martin Fowler, Kent Beck, and DHH had a live hangout about TDD (Test Driven Development), where one of the most recurrent topics was about developers mocking too much. Interestingly, the three of them claimed to almost never use mocks.
Some others prefer to see the use of mocks as a way to think about how classes should collaborate, as in the Growing Object-Oriented Systems Guided by Tests book, by Freeman and Pryce.
Spadini et al. in two recent papers [1,2] showed that Java developers tend to indeed mock classes that access some infrastructure more often than not. Their paper also show that the use of mocking introduces a strong coupling between the test code and production code by observing that, in many cases, when the production class changed an internal detail, the developer had also to change the test code.
Therefore, the pragmatic advice is for you as a developer to consider whether the use of mocks really fits the situation you are in. And be careful with possible shallow tests.
[1] Spadini, D., Aniche, M., Bruntink, M., & Bacchelli, A. (2017, May). To mock or not to mock?: an empirical study on mocking practices. In Proceedings of the 14th International Conference on Mining Software Repositories (pp. 402-412). IEEE Press.
[2] Spadini, D., Aniche, M., Bruntink, M., & Bacchelli, A. (2018). Mock Objects For Testing Java Systems – Why and How Developers Use Them, and How They Evolve. In Empirical Software Engineering Journal.
Further reading:
Pereira, Fabio. Mockists are dead. Long live classicists. URL: https://www.thoughtworks.com/insights/blog/mockists-are-dead-long-live-classicists. 2014.
Automated Software Testing: Practical Skills for Java Developers by TU Delft OpenCourseWare is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Based on a work at https://online-learning.tudelft.nl/courses/automated-software-testing-practical-skills-for-java-developers/.