title: How to create testable code using .Net IO classes?
body: <p>I want to create unit testable code that mocks out the calls to the .Net System.IO classes, so I can really unit test instead of depending on the filesystem.
  I am using the <a href="http://systemwrapper.codeplex.com/" rel="nofollow">SystemWrapper</a> classes to wrap around the BCL classes.</p>
  
  <p>I am trying to get a simple example working to see whether a file exists.</p>
  
  <p>The problem I am having is that injecting the dependency in the class doesn't work because instantiating the dependency (through <a href="http://structuremap.net/structuremap/" rel="nofollow">StructureMap</a>) requires knowing what constructor parameter to pass, which won't be available at that time, also there is no default constructor. </p>
  
  <p>sample code:</p>
  
  <pre><code>// don't want to create dependency here like so
  //IFileInfoWrap fileInfoWrap = new FileInfoWrap(filename);
  
  // using service locator (anti-pattern?!) since it can't be 
  // injected in this class
  var fileInfoWrap = ObjectFactory.GetInstance&lt;IFileInfoWrap&gt;(
      new ExplicitArguments(new Dictionary&lt;string, object&gt;
      {
          {"fileName", filename}
      }));
  
  Console.WriteLine("File exists? {0}",  fileInfoWrap.Exists); 
  </code></pre>
  
  <p>What I don't like is that the dependency is not injected, ObjectFactory should not be here (but I see no other way of creating this).
  The ExplicitArguments makes it messy and the argument-name is a magic-string.</p>
  
  <p>For me to get this to work  StructureMap config class needs to know explict which constructor I want to use ( I just started with StructureMap so this might not be the right way to set it up):</p>
  
  <pre><code>ObjectFactory.Initialize(x =&gt;
  {
      x.Scan(scan =&gt;
      {
          scan.AssembliesFromPath(".");
          scan.RegisterConcreteTypesAgainstTheFirstInterface();
          scan.WithDefaultConventions();
      });
  
      // use the correct constructor (string instead of FileInfo)
      x.SelectConstructor(() =&gt; new FileInfoWrap(null as string));
  
      // setting the value of the constructor
      x.For&lt;IFileInfoWrap&gt;()
          .Use&lt;FileInfoWrap&gt;()
          .Ctor&lt;string&gt;("fileName")
          .Is(@".");
  });
  </code></pre>
  
  <p>Does anyone found a better solution to create testable code against the System.IO classes?
  I know part of the problem is in the design of the System.IO classes.</p>