Removing the problems with instance creation
In this recipe, we will first test an existing class that uses new
to instantiate an object which performs complex logic; then, we'll refactor it. The problem with the new
operator is that it's very difficult to mock the created instance. An object's collaborators should be passed as parameters of the constructor or somehow injected via the dependency injection system.
Getting ready
Let's assume that our system under test is a system that generates a new identity for a given person who can have a name, an age, and siblings. Note that the following snippet presents a poorly designed class:
public class BadlyDesignedNewPersonGenerator { public Person generateNewIdentity(Person person) { NewIdentityCreator newIdentityCreator = new NewIdentityCreator(); String newName = newIdentityCreator.createNewName(person); int newAge = newIdentityCreator.createNewAge(person); List<Person> newSiblings = newIdentityCreator...