Hosted by:
Unit testing expertise at your fingertips!
Home | Discuss | Lists

Replace Dependency with Test Double

The 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.

Implementation Notes

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.

Page generated at Wed Feb 09 16:39:52 +1100 2011

Copyright © 2003-2008 Gerard Meszaros all rights reserved

All Categories
Introductory Narratives
Web Site Instructions
Code Refactorings
Database Patterns
DfT Patterns
External Patterns
Fixture Setup Patterns
Fixture Teardown Patterns
Front Matter
Result Verification Patterns
Test Double Patterns
Test Organization
Test Refactorings
Test Smells
Test Strategy
Value Patterns
XUnit Basics
xUnit Members
All "Test Refactorings"
Extract Testable Component
Inline Resource
Make Resource Unique
Minimize Data
Replace Dependency with Test Double
Setup External Resource