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 :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


eight + 5 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close