Table of contents
Are true mocks evil?
The content here is under the Attribution 4.0 International (CC BY 4.0) license
The advent of mocking frameworks has revolutionized the way we write tests, but it has also sparked a debate about the ethics and effectiveness of using true mocks. In this article, we will explore the concept of true mocks, their advantages and disadvantages, and whether they are truly evil or just misunderstood.
What are true mocks?
By definition, a true mock is a test double that simulates the behavior of a real object in a controlled way. It allows you to isolate the unit of code being tested from its dependencies, enabling you to focus on the logic of the unit itself. True mocks are often used in unit tests to verify interactions between objects and to ensure that the unit behaves as expected. However, true mocks can also lead to a number of issues, such as:
- Over-specification: True mocks can encourage developers to specify too much about the behavior of the unit being tested, leading to brittle tests that break easily when the implementation changes.
- False sense of security: True mocks can give developers a false sense of security, as they may pass tests even if the implementation is incorrect. This can lead to a false sense of confidence in the codebase.
- Complexity: True mocks can add complexity to the test code, making it harder to read and maintain. This can lead to a situation where the tests become more complex than the code being tested.
A common association with true mocks is the usage of them in the TDD based on the London school of TDD, which emphasizes the use of mocks to drive the design of the code. This approach can lead to a situation where the tests become too tightly coupled to the implementation, making it difficult to change the code without breaking the tests.
Design
In that sense, the design of the test case become the first point of attention. The test case should be designed to focus on the behavior of the unit being tested, rather than the implementation details.
This means that the understanding of collaborations and how to use them is crucial, (Freeman & Pryce, 2009) in the book “Growing object-oriented software, guided by tests}” help to define the types of collaborators, to help the design. Which turns the focus of the definition on the unit. What is a unit? Is it the class? Is it the method? Is it the interaction between the class and its collaborators?
(Rivero, 2025) elaborates further on the aspects of what is a unit, and how to define it.
Another approach
TDD is also practiced with other types of test-doubles, not only true mocks . Using Fakes for testing is an alternative to that.
Reference
- Freeman, S., & Pryce, N. (2009). Growing object-oriented software, guided by tests. Pearson Education.
- Rivero, M. (2025). The class is not the unit in the London school style of TDD. Codesai Blog. https://codesai.com/posts/2025/03/mockist-tdd-unit-not-the-class