Testing and Static Methods
I'm working with a large codebase at the moment, trying to write unit tests to ensure that the changes I'm making aren't compromising the existing code.
For some of the code, this is easy. For other pieces, not so much.
One area that I'm finding difficult is in the area of static methods. Historically, I've been a fan of static methods for some scenarios. But, now I'm finding them a bit of a pain.
I stumbled upon the GoogleTesting blog and a post that says it well:
Here is another way of thinking about it. Unit-testing needs seams, seams is where we prevent the execution of normal code path and is how we achieve isolation of the class under test. seams work through polymorphism, we override/implement class/interface and than wire the class under test differently in order to take control of the execution flow. With static methods there is nothing to override. Yes, static methods are easy to call, but if the static method calls another static method there is no way to overrider the called method dependency.
There's no way that I'd even consider removing the static methods from the codebase I'm working on - they're too integral to the architecture of the system, and I'm not going to introduce any inconsistencies, for that way lies madness (or, unmaintainability, at the very least).
But, I do need to find a way to introduce a seam or two to support testability.
Comments
Another way to introduce
Another way to introduce seams is to use the ServiceLocator pattern (rather than the inheritance-based approaches to DI). Requires that the static methods look up the services they require, and respect the case where, in test mode, they are given back a different service from what they are given in production mode. (This is not service in the SOA sense, just the general sense).