A lack of dependency injection

This is one of the smells often detected in a legacy codebase. As there is no need to test the classes in isolation, the collaborators are instantiated where they are needed, putting the responsibility for creating collaborators and using them in the same class.

Here's an example, using the new operator:

public class BirthdayGreetingService { 
 
  private final MessageSender messageSender; 
 
  public BirthdayGreetingService() { 
    messageSender = new EmailMessageSender(); 
  } 
 
  public void greet(final Employee employee) { 
    messageSender.send(employee.getAddress(),      "Greetings on your birthday"); 
  } 
} 

In the current state, the BirthdayGreeting service is not unit-testable. It has the dependency to EmailMessageSender hardcoded ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.