Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock DirectoryInfo class?

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 );
like image 207
O.O Avatar asked Jun 22 '12 15:06

O.O


2 Answers

I see two obvious choices:

  1. Replace DirectoryInfo with your own wrapper implementation there (not ideal)
  2. 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;
  }
}
like image 120
Paul Phillips Avatar answered Sep 28 '22 12:09

Paul Phillips


The link gives example how to mock File class you need to do similar for DirectoryInfo How do you mock out the file system in C# for unit testing?

like image 37
HatSoft Avatar answered Sep 28 '22 13:09

HatSoft