How to deal with static utility classes when designing for testability

Posted by Benedikt on Programmers See other posts from Programmers or by Benedikt
Published on 2012-04-27T08:48:14Z Indexed on 2012/12/20 11:13 UTC
Read the original article Hit count: 460

Filed under:
|
|
|

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:

  1. Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.
  2. 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.
  3. 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?

© Programmers or respective owner

Related posts about java

Related posts about testing