How to mock DirectoryInfo class?

.net-2.0, c#, mocking

Solution

I see two obvious choices:

- Replace `DirectoryInfo` with your own wrapper implementation there (not ideal)

- Create a factory that can make `IDirectoryInfoWrapper` instances. You could make a `Create` function with overloads for each constructor you wanted to use.

I'm assuming you are doing this with dependency-injection, which would mean now you just inject that factory into any class needing to create new directory info objects.

Also, you would want to modify the wrapper interface to expose that `Exists` property

Edit: if you're doing this to try to unit-test something (which seems likely) then you might try reading Misko Hevery. Every time you use the `new` operator in C#, you have a point where you cannot inject something at runtime. This makes it very difficult to test anything using `new` in any but the most trivial of cases. For anything that isn't a simple data object, I pretty much always use a factory.

Edit II:

You're delegating the construction to the factory, so that's where you use the `DirectoryInfo` real constructor:

class Factory : IFactory 
{
  IDirectoryInfoWrapper Create(string arg)
  {
    var dirInfo = new DirectoryInfo(arg);
    var wrapper = new DirectoryInfoWrapper(dirInfo);
    return wrapper;
  }
}

Problem

So far I created the following interface: ``` public interface IDirectoryInfoWrapper { public IFileInfoWrapper[] GetFiles(string searchPattern, SearchOption searchType); public IDirectoryInfoWrapper[] GetDirectories(); } ``` I've been going through the code replacing DirectoryInfo with `IDirectoryInfoWrapper`. All was going well until I found this: ``` // Check that the directory is valid DirectoryInfo directoryInfo = new DirectoryInfo( argPath ); if ( directoryInfo.Exists == false ) { throw new ArgumentException ("Invalid IFileFinder.FindFiles Directory Path: " + argPath); } ``` It makes no sense to put the constructor in the interface, so what should I do with this line of code: ``` DirectoryInfo directoryInfo = new DirectoryInfo( argPath ); ```

Original source

Related problems