TDD – Helper Static Methods in Test-Driven Development

ctddtestingunit testing

I am creating an application which will be testable(unit + integration). In this application I have a FileHelper static class,

public static class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    } 
    public static void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}

But due to static I think it is not testable. How to make this class testable?

Best Answer

To say that they're not testable is inaccurate. They're very testable, but they're not mockable and thus they are not test-friendly. That is, every time you test a unit of code that calls this method, you have to test the method. If the method is ever broken, many tests will fail and it won't be obvious why.

With that in mind, the solution is fairly obvious. Make it a non-static class, extract an interface with all the methods in and pass your helper into every class that needs it, preferably through the constructor, and preferably using an IOC Container.

public class FileHelper : IFileHelper
{
    public void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }

    public void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}

public interface IFileHelper
{
    void ExtractZipFile(Stream zipStream, string location);
    void CreatePageFolderIfNotExist(string directory);

    .......................................................
    .......................................................
}

public class MyClass
{
     private readonly IFileHelper _fileHelper;

     public MyClass(IFileHelper fileHelper)
     {
         _fileHelper = fileHelper;
     }
}
Related Topic