Friday, May 20, 2011

Refactoring Code with Static Dependencies for Testability

Methods that have dependencies on static methods can be difficult to test. In this example we have a dependency that we obtain via a static method that we do not have control over and we want to test the surrounding code.

public void myMethod(Long id) {
// ...
Dependency dependency = DependencyUtil.getDependency();
// ...
}

We can refactor this to:

public void myMethod(Long id) {
Dependency dependency = DependencyUtil.getDependency();
myMethod(dependency);
}

void myMethod(Long id, Dependency dependency) {
// ...
doSomething(dependency);
// ...
}

We overload the method signature and preserve the public API. We make the new method have default access to make it testable. We can now mock Dependency however we like.

No comments: