
143
Installing the Test Double
Before we exercise the SUT, we need to “install” any Test Doubles on which
our test depends. The term “install” here serves as a generic way to describe the
process of telling the SUT to use our Test Double, regardless of the exact details
regarding how we do it. The normal sequence is to instantiate the Test Double,
confi gure it if it is a Confi gurable Test Double, and then tell the SUT to use the
Test Double either before or as we exercise the SUT. There are several distinct
ways to “install” the Test Double, and the choice between them may be as much
a matter of style as of necessity if we are designing the SUT for testability. Our
choices may be much more constrained, however, when we try to retrofi t our
tests to an existing design.
The basic choices boil down to Dependency Injection (page 678), in which the
client software tells the SUT which DOC to use; Dependency Lookup (page 686),
in which the SUT delegates the construction or retrieval of the DOC to another
object; and Test Hook, in which the DOC or the calls to it within the SUT
are modifi ed.
If an inversion of control framework is available in our language, our tests
can substitute dependencies without much additional work on our part. This
removes the need for building in the Dependency Injection or Dependency
Lookup mechanism.
Dependency Injection
Dependency Injection is a class of design decoupling in which the client tells the
SUT which DOC to use at runtime (Figure 11.10). The test-driven development
(TDD) movement has greatly increased its popularity because Dependency Injec-
tion makes for more easily tested designs. This pattern also makes it possible to
reuse the SUT more broadly because it removes knowledge of the dependency
from the SUT; often the SUT will be aware of only a generic interface that the
DOC must implement. Dependency Injection comes in several specifi c fl avors,
with the choice between them being largely a matter of taste:
• Setter Injection (see Dependency Injection): The SUT accesses the
DOC through a public attribute (i.e., a variable or property). The test
explicitly sets the attribute after instantiating the SUT to installing the
Test Double. The SUT may have previously initialized the attribute
with the real DOC in its constructor (in which case the test is replac-
ing it) or the SUT may use Lazy Initialization [SBPP] to initialize the
attribute (in which case the SUT will not bother to install the real
DOC).
Testing with Doubles