While watching the first of JP Boodhoos screencast series I discovered that a concept that I used in order to introduce testing to developers who work mostly in legacy code (I’m using Michael Feathers terminology here) is in fact a well known pattern. Let me give you an example. You’ve got a class that you want test, but this class somehow depends on an untestable resource like for instance a webservice. You don’t have some kind of dependency inversion to you’re hand and have to solve this problem on your own. A short example:
1 2 3 4 5 6 7 8 9 10 11 12 | |
What I mostly recommend in such a situation is
- Extract or isolate the ugly (Quote from Jeremy Miller) which is the webservice call here.
- Introduce an interface that shields the class from the webservice call.
- Make the whole class rely on the abstraction.
- Use two constructors. I mostly reffered to them as the opened and the closed constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
With that you can easily replace the untestable code with some kind of testdouble like a stub or a mock.
1 2 3 4 5 6 7 8 9 10 11 12 | |
Today I learned that this is also called POOR MANS DEPENDENCY INJECTION.
P.S.: Mabe the example is not the best one but I didn’t want to go into something like Foo and Bar again. Besides that it’s only a simplified example. Consider that before throwing eggs and tomatos at me :-).
P.S.2: An alternative to this approach which doesn’t require a new interface is “Extract & Override”.