October 18, 2018
Hot Topics:

Getting Test Doubles in Place

  • January 3, 2008
  • By Jeff Langr
  • Send Email »
  • More Articles »

Listing 8: Injection via subclass override.

public class Portfolio {
// ...
   public int value() {
      StockLookupService service = createStockLookupService();

      int total = 0;
      for (Map.Entry<String,Integer>
         entry: holdings.entrySet()) {
         String symbol = entry.getKey();
         int shares = entry.getValue();
         total += service.currentValue(symbol) * shares;
      return total;

   protected StockLookupService createStockLookupService() {
      return new NASDAQLookupService();
// ...

The downside of injecting via subclass override is that, once again, I violate encapsulation. My test knows more about the implementation details of Portfolio than it would otherwise. The trouble is that I can no longer change such details without impacting or possibly breaking tests. That's an acceptable cost because I value the ability to test far more than notions of design perfection. But, it's a reminder that there might be trouble if I take this concept too far, and let my tests know more significant amounts of detail about the targets they verify.


There are other interesting ways of injecting test doubles than I presented here. I might, for example, consider using aspects. But these three techniques—constructor/setter injection, factory injection, and subclass override injection—are the ones that I consistently use. Using these different injection techniques gives me a bit more flexibility when it comes to incorporating fakes into a system. But, an important thing I must remember is that the very introduction of these fakes implies that I now have a "hole" in my system—something that I will be unable to unit test. I can't neglect my integration tests!

About the Author

Jeff Langr is a veteran software developer with over a quarter century of professional software development experience. He's authored two books and over 50 published articles on software development, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft dot com.

Page 3 of 3

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


Thanks for your registration, follow us on our social networks to keep up-to-date