How to deal with static utility classes when designing for testability
- by Benedikt
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:
In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.
I have several ideas for solving this problem:
Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.
Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.
Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.
But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.
What is the best strategy to keep classes that use these static helpers testable?