Frank Jusnes
Frank Jusnes

Reputation: 185

Challenge making code testable

I'm refactoring legacy code to make it (unit) testable. I have two classes implementing the same interface, as shown below. In one of the classes I have an external dependency towards DirectoryEntry. My suggested way of dealing with that is to create an IDirectoryEntry interface, and pass the directory entry as a parameter to the GetGroups method. The problem is that that would break IMyInterface.

What would a better way to refactor this code?

public interface IMyInterface
{
    List<string> GetGroups();
}

public class MyFirstClass : IMyInterface
{
    public List<string> GetGroups()
    {
        ..
        var directoryEntry = new DirectoryEntry(path);
        ..
        return something;
    }
}

public class MySecondClass : IMyInterface
{
    public List<string> GetGroups()
    {
        return somethingElse;
    }
}

Regards, Frank

Upvotes: 0

Views: 158

Answers (1)

Dissimilis
Dissimilis

Reputation: 460

If you have external dependency in only one of your classes you probably don't want to pass it as a parameter. Better way would be to pass it in a constructor:

public class MyFirstClass : IMyInterface
{
    private IDirectoryEntry _entryAccessor;
    public MyFirstClass(IDirectoryEntry entryAccessor)
    {
         _entryAccessor = entryAccessor;
    }
    public List<string> GetGroups()
    {
        var directoryEntry = _entryAccessor.Do(path);
        return something;
    }
}

Upvotes: 2

Related Questions