O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required