Java tips, observations, bugs and problems from the world of Spring, Weblogic, Oracle, MySQL and many other technologies...

Thursday, 1 December 2011

More on Creating Stubs for Legacy Code - Testing Techniques 7

In my last blog, I talked about dealing with the badly behaved untestable1SitePropertiesManager 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:

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:

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.