Java Reference
In-Depth Information
constructor that still initializes the logger and configuration field members with
default implementations.
With this refactoring, we've provided a trapdoor for controlling the domain
objects from your tests. We retain backward compatibility and pave an easy refactor-
ing path for the future. Calling classes can start using the new constructor at their
own pace.
Should you worry about introducing trapdoors to make your code easier to test?
Here's how Extreme Programming guru Ron Jeffries explains it:
My car has a diagnostic port and an oil dipstick. There is an inspection port on the side of
my furnace and on the front of my oven. My pen cartridges are transparent so I can see if
there is ink left.
And if I find it useful to add a method to a class to enable me to test it, I do so. It
happens once in a while, for example in classes with easy interfaces and complex inner
function (probably starting to want an Extract Class).
I just give the class what I understand of what it wants, and keep an eye on it to see
what it wants next. 1
Design patterns in action: Inversion of Control
Applying the IoC pattern to a class means removing the creation of all object
instances for which this class isn't directly responsible and passing any
needed instances instead. The instances may be passed using a specific con-
structor, using a setter, or as parameters of the methods needing them. It
becomes the responsibility of the calling code to correctly set these domain
objects on the called class. 2
IoC makes unit testing a breeze. To prove the point, let's see how easily we can now
write a test for the findAccountByUser method: 2
public void testFindAccountByUser() {
MockLog logger = new MockLog();
MockConfiguration configuration = new MockConfiguration();
configuration.setSQL("SELECT * [...]");
DefaultAccountManager am = new DefaultAccountManager(logger,
configuration);
Account account = am.findAccountForUser("1234");
// Perform asserts here
[...]
}
B
C
D
1
Ron Jeffries, on the TestDrivenDevelopment mailing list: http://groups.yahoo.com/group/testdrivendevel-
opment/message/3914.
2
See the Jakarta Avalon framework for a component framework implementing the IoC pattern ( http://
avalon.apache.org).
 
 
 
 
 
 
 
Search WWH ::




Custom Search