DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Transactional Outbox Patterns Step by Step With Spring and Kotlin
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Never Use Credentials in a CI/CD Pipeline Again

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Transactional Outbox Patterns Step by Step With Spring and Kotlin
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Never Use Credentials in a CI/CD Pipeline Again
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. More on Creating Stubs for Legacy Code - Testing Techniques 7

More on Creating Stubs for Legacy Code - Testing Techniques 7

Roger Hughes user avatar by
Roger Hughes
·
Dec. 04, 11 · Interview
Like (0)
Save
Tweet
Share
3.60K Views

Join the DZone community and get the full member experience.

Join For Free
In my last blog, I talked about dealing with the badly behaved untestable1 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 blog2 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

 

From http://www.captaindebug.com/2011/12/more-on-creating-stubs-for-legacy-code.html

Stub (distributed computing) unit test

Opinions expressed by DZone contributors are their own.

Trending

  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  • Transactional Outbox Patterns Step by Step With Spring and Kotlin
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Never Use Credentials in a CI/CD Pipeline Again

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: