I am adding new functionality into a legacy application. For my new classes I have introduced Unit Testing. I still need to work with the existing code.
One of the problems I face is that a lot of static methods have been used.
Below is an example of a class I need to use:
public class HelperClass
{
public static bool ReturnSomething()
{
return true;
}
}
My fix for making this testable:
public interface IHelperClass
{
bool ReturnSomething();
}
public class HelperClass : IHelperClass
{
public static bool ReturnSomething()
{
return true;
}
bool IHelperClass.ReturnSomething()
{
return ReturnSomething();
}
}
A class that used to use the static method, but by introducing a property (initialized by the constructor), that now uses the testable class. I can inject a mock using this property. Note that I could have used a factory for injecting the mock, however I wanted to keep it simple for the example.
public class UserClass
{
public UserClass()
{
// Initialize with default
HelperClass = new HelperClass();
}
public IHelperClass HelperClass { get; set; }
}
My advantages:
- No need to modify existing code that is using the static class
- Code can be migrated from static to a testable instance
- I can reuse the existing concrete class
My disadvantages:
- Needed to modify legacy code that needs to be tested. Not always possible when in external assembly.
- PropertyName is the same as the class Name
I welcome any feedback!