Mocking as a Design Smell

Listen to this post

In TDD, we seek to create granular, unique tests, tests that fail for a single reason only. To achieve this, when testing an entity that has dependencies, a typical way to prevent the test from failing for the wrong reason is to create mocks of those dependencies. A mock can be simply a replacement that the test controls.

As with every part of TDD, mocking can tell you things about the design of your system.

What might be obvious is this: when a large number of mocks are needed, this indicates a large number of dependencies that must be dealt with when testing a given entity. A large number of dependencies indicates a lot of coupling, which can be problematic when maintaining the system.

However, mocking also can tell us something else. Mocks, ideally, are kept very simple. We want them to have no way to cause the test to fail and thus mislead us. We also don’t want to create complex tests for the mocks themselves, as this adds to the testing burden.

If we find that we cannot create a mock simply, this means that the dependency it replaces may be too complex. It may lack cohesion or do too much, and the need for a complex mock is reflecting this.

“Smells” do not guarantee you have a problem, but they are worth looking into.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.