public interface MyInterface {
|
Then you can use that field like a static variable, most likely as an old-school (pre-dependency-injection) singleton instance.
There are two problems with this as far as testability is concerned. First, you have the usual difficulty you get with static instances in unit tests, namely, that you cannot insert a mock, stub, or fake in all of the places where it is referenced. But if that is not enough to convince you to not use this pattern (hint: it should be), there is another problem that is arguably even more insidious.
Let's say that by some stroke of luck, you are trying to test a class that does not make static reference to the singleton instance and accepts the dependency properly. Now, when you go to create a mock or fake implementation of MyInterface for use in the test, Java still has to instantiate MyInterfaceImpl at classload-time. Depending on what all that involves, this may be expensive, unstable, or flat-out fail in the test environment, thereby thwarting your efforts to properly unit-test.
Obviously, the easiest way to solve this problem is to avoid it in the first place. But if you happen to run into it in a legacy system, you can start migrating away from it gradually by simply moving the instance to another class, or by using something like the value-holder pattern or initialization-on-demand holder idiom that moves the creation of the instance out of the classload sequence for the interface.
No comments:
Post a Comment