How to refactor and make static class code testable?

How to refactor and make static class code testable?

We commonly come across a problem where we need to write a unit test case of an existing application and found that it has tons on dependency of static methods.

 

Here we would be directly jumping on how to refactor your code to get rid of static methods meanwhile you can go through the following blogs to understand why static methods hinder testability

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/
http://blog.goyello.com/2009/12/17/why-static-classes-are-evil/

 

So here we go, we have a problem statement where we have a static class which is being used by another class

public class Utility
{
public static void PerformTask()
{
// your code
}
}

public class TestClass
{
public void TestMethod()
{
// Initial piece of code
Utility. PerformTask();
// Rest of your code
}
}

We are going to solve this problem in 3 steps.
1st Step: Create interfaces having logical segregation of task being performed by the Utility class, for us, we have just one method so one interface would be sufficient.

public interface IUtility
{
void PerformTask();
}

2nd Step: Create a concrete class for each interface created in step 1 and have the desired implementation, there which was initially done in your static methods.

public class Utility : IUtility
{
public void PerformTask()
{
// your code
}
}

3rd Step: Inject the correct Interface in your desired class where you were calling the static methods.

public class TestClass
{
private IUtility utility;

public Client(IUtility utility)
{
this.utility = utility;
}

public void TestMethod()
{
// Initial piece of code
utility. PerformTask();
// Rest of your code
}
}

Aha, we are done now. You are free to resolve your interfaces with desired class instance and create mock for its testing and yes, you are free to you any DI framework.

Shashank Bisen

Shashank Bisen is curious blogger and speaker who love to share his knowledge and experience which can help anyone in their day to day work. 

One Comment to “How to refactor and make static class code testable?”

Comments are closed.