Replace Dependency with Test DoubleThe book has now been published and the content of this chapter has likely changed substanstially.
The dependencies of an object being tested are getting in the way of running tests.
Break the dependency by replacing a depended-on component with a Test Double.
The first step is to decide which form of dependency substitution we want to do. Dependency Injection (page X) is best for unit tests while Dependency Lookup (page X) often works better for customer tests. We then refactor the system under test (SUT) to support this or design the capability into the SUT as we do test-driven development. The next decision is whether to use a Fake Object (page X) or a Test Stub (page X) or Mock Object (page X) based on how it will be used by the test. This decision is described in Using Test Doubles.
If we are using a Test Stub or Mock Object, we'll need to decide whether we want to use a Hard-Coded Test Double (page X) or a Configurable Test Double (page X). The trade-offs are discussed in the previously mentioned chapter and in the detailed descriptions of the patterns. Once we have decided, that dictates the shape of our test. Mock Object tests are more "front loaded" by the construction of the Mock Object.
And finally, we modify our test to construct, optionally configure, and then install the Mock Object. We may also have to add a call to the verification 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 implementation. Then, we use this interface as the type of the variable that holds the reference to the substitutable dependency.
Copyright © 2003-2008 Gerard Meszaros all rights reserved