
739
objects in the Shared Fixture (page 317) is overkill for any one test, we can
use a series of Extract Method [Fowler] refactorings to create a set of Creation
Methods (page 415), which we then call from the tests. Next, we remove the
calls to the Creation Methods from the setUp method and put them into only
those Test Methods that require that part of the original fi xture. The fi nal step
would be to convert any fi xture-holding instance variables into local variables.
Replace Dependency with Test Double
The dependencies of an object being tested get in the way of running tests.
Break the dependency by replacing a depended-on component
with a Test Double.
Implementation Notes
The fi rst step is to choose the form of dependency substitution. Dependency
Injection (page 678) is the best option for unit tests, whereas Dependency Look-
up (page 686) often works better for customer tests. We then refactor the SUT
to support this choice or design the capability into the SUT as we do test-driven
development. The next decision is whether to use a Fake Object (page 551), a
Test Stub (page 529), a Test Spy (page 538), or a Mock Object (page 544) based
on how the Test Double will be used by the test. This decision is described in
Chapter 11, Using Test Doubles.
If we are using a Test Stub or Mock Object, we must decide whether we
want to use a Hard-Coded Test Double (page 568) or a Confi gurable Test
Double (page 558). The trade-offs are discussed in Chapter 11 and in the
detailed descriptions of the patterns. That decision then dictates the shape of
our test—for example, Tests that use Mock Objects are more “front-loaded”
by the construction of the Mock Object.
Finally, we modify our test to construct, optionally confi gure, and then install
the Mock Object. We may also have to add a call to the verifi cation method for
some kinds of Mock Objects. In statically typed languages, we may have to do
an Extract Interface [Fowler] refactoring before we can introduce the fake imple-
mentation. We then use this interface as the type of the variable that holds the
reference to the substitutable dependency.
Replace Dependency with Test Double
Replace
Dependency
with Test
Double