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 );
I see two obvious choices:
DirectoryInfo
with your own wrapper implementation there (not ideal)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;
}
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With