Understanding When Test Doubles Are Appropriate

Understand how Mock objects are used to record interactions between SUT and its collaborators, allowing verification of method calls and parameters passed.

Mock objects are a useful kind of test double, as we have seen. But they are not always the right approach. There are some situations where we should actively avoid using mocks. These situations include overusing mocks, using mocks for code we don’t own, and mocking value objects. We’ll look at these situations next. Then, we’ll recap with general advice for where mocks are typically useful. Let’s start by considering the problems caused when we overuse mock objects.

The pitfall of overusing mock objects

At first glance, using mock objects seems to solve a number of problems for us. Yet if used without care, we can end up with very poor-quality tests. To understand why, let’s go back to our basic definition of a TDD test. It’s a test that verifies behaviors and is independent of implementations. If we use a mock object to stand in for a genuine abstraction, then we’re complying with that.

Get hands-on with 1400+ tech skills courses.