Refactoring: Extract and override factory method
A refactoring is a code change that leaves the original functionality intact, but changes the design of the code so that it's cleaner, more efficient, and easier to test. This section offers a step-by-step description of the Extract and Override factory method refactoring.
Problem: The object being tested creates a collaborator object. This collaborator must be replaced with a mock object.
Code before refactoring
|
Solution: Extract the creation code into a factory method, override this factory method in a test subclass, and then make the overridden method return a mock object instead. Finally, if practical, add a unit test that requires the original object's factory method to return an object of the correct type:
Code after refactoring
|
This refactoring enables the unit test code shown in Listing 1:
Listing 1. Unit test code
|
Roles
This design introduces the following roles played by objects in the system:
- Target object: The object being tested
- Collaborator object: The object created or obtained by the target
- Mock object: A subclass (or implementation) of the collaborator that follows the mock object pattern
- Specialization object: A subclass of the target that overrides the creation method to return a mock instead of a collaborator
View Unit testing with mock objects Discussion
Page: 1 2 3 4 5 6 Next Page: Mechanics