How to make fun of the DirectoryInfo class?

So far I have created the following interface:

public interface IDirectoryInfoWrapper { public IFileInfoWrapper[] GetFiles(string searchPattern, SearchOption searchType); public IDirectoryInfoWrapper[] GetDirectories(); } 

I am looking at code replacing DirectoryInfo IDirectoryInfoWrapper . Everything went 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 ); 
+6
source share
2 answers

I see two obvious options:

  • Replace DirectoryInfo your own shell implementation (not perfect)
  • Create a factory that can instantiate IDirectoryInfoWrapper . You can make the Create function with overloads for each constructor that you want to use.

I assume that you are doing this with dependency injection, which means that now you just enter the factory in any class that needs to create new directory information objects.

In addition, you want to change the shell interface to show that the Exists property

Edit : if you do this to try to do partial testing (which seems likely), you can try reading Misko Hevery . Each time you use the new operator in C #, you have a point at which you cannot enter anything at runtime. This makes it very difficult to verify anything using new in any, but most trivial case. For anything that is not a simple data object, I almost always use a factory.

Edit II :

You delegate the factory construct, so when you use the real DirectoryInfo constructor:

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

The link gives an example of how to mock a file class that you need to do the same for DirectoryInfo. How do you mock a C # file system for unit testing?

+1
source

Source: https://habr.com/ru/post/918772/


All Articles