More on Creating Stubs for Legacy Code – Testing Techniques 7

In my last blog, I talked about dealing with the badly behaved untestable(1) SitePropertiesManager class and how to create stubs by extracting an interface. But what happens when you don’t have access to the source code of the legacy class because it’s locked away inside a third party JAR file? The answer is one of those things that you really don’t think about, but when you see it you realise that it’s fairly obvious.

To demonstrate this, I’m going to re-write the code from my last blog (2) that tests my simple AddressService. The scenario is the same, the AddressService has to load a site property and decide whether or not to return an address:

public Address findAddress(int id) {

    logger.info("In Address Service with id: " + id);

    Address address = Address.INVALID_ADDRESS;

    if (isAddressServiceEnabled()) {
      address = addressDao.findAddress(id);
      address = businessMethod(address);
    }

    logger.info("Leaving Address Service with id: " + id);
    return address;
  }

  private boolean isAddressServiceEnabled() {

    return new Boolean(propManager.findProperty("address.enabled"));
  }

…except, I’m going to pretend that SitePropertiesManager is locked away inside a JAR file.

All the points about making legacy code more testable that I raised previously still stand: you need to move to dependency injection using a SpringFactoryBean implementation and stop relying on the static factory method getInstance(). You also need a way of creating a stub that allows you to isolate you code from the database and file system that’s happily used by our rogue class SitePropertiesManager. In this case, as the class is locked inside a JAR file, you can’t simply extract an interface, you have to be slightly more cunning and use inheritance. Writing a stub using inheritance is pretty trivial and only takes a few lines of code as demonstrated below:

public class StubSitePropertiesUsingInheritance extends SitePropertiesManager {

  private final Map<String, String> propMap = new HashMap<String, String>();

  public void setProperty(String key, String value) {
    propMap.put(key, value);
  }

  @Override
  public String findProperty(String propertyName) {
    return propMap.get(propertyName);
  }
}

The big idea here is that I can now polymorphically inject my stub instance in to my AddressService class without it knowing that it’s been fooled.

public class LegacyAddressServiceUsingInheritanceTest {

  private StubAddressDao addressDao;

  private StubSitePropertiesUsingInheritance stubProperties;

  private LegacyAddressService instance;

  @Before
  public void setUp() {
    instance = new LegacyAddressService();

    stubProperties = new StubSitePropertiesUsingInheritance();
    instance.setPropertiesManager(stubProperties);
  }

  @Test
  public void testAddressSiteProperties_AddressServiceDisabled() {

    /* Set up the AddressDAO Stubb for this test */
    Address address = new Address(1, "15 My Street", "My Town", "POSTCODE", "My Country");
    addressDao = new StubAddressDao(address);
    instance.setAddressDao(addressDao);

    stubProperties.setProperty("address.enabled", "false");

    Address expected = Address.INVALID_ADDRESS;
    Address result = instance.findAddress(1);

    assertEquals(expected, result);
  }

  @Test
  public void testAddressSiteProperties_AddressServiceEnabled() {

    /* Set up the AddressDAO Stubb for this test */
    Address address = new Address(1, "15 My Street", "My Town", "POSTCODE", "My Country");
    addressDao = new StubAddressDao(address);
    instance.setAddressDao(addressDao);

    stubProperties.setProperty("address.enabled", "true");

    Address result = instance.findAddress(1);

    assertEquals(address, result);
  }
}

You may well ask: why not always use inheritance and the answer is that the downside to this technique is that the test code is tightly coupled to the wild SitePropertiesManager class. This is not too much of a problem in this case and, being the pragmatic programmer, I guess that this doesn’t really matter as having code that’s neat, tested and reliable is better than having code that’s loosely couple, but without unit tests.


(1) Designed without taking unit testing in to consideration.
(2) The source code is available from GitHub at:

    git://github.com/roghughe/captaindebug.git

Reference: More on Creating Stubs for Legacy Code – Testing Techniques 7 from our JCG partner  Roger Hughes at the Captain Debug’s Blog .

Related Articles :

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


2 + four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books