title: Mocking StreamWriter (C# Moq)
body: <p>I am writing a method that will write to a text file. I am still trying to wrap my head around Dependency Inversion.</p>
  
  <p>The issue I appear to be having is with mocking StreamWriter.</p>
  
  <p>Here is my test, I commented out one of the setup lines, as this is where my issue is.</p>
  
  <pre><code>[Test]
      public void WriteToAutomationLog_FileDoesNotExist_CreateFile()
      {
          //arrange
          mockDirectoryWrapper.Setup(_ =&gt; _.Exists(It.IsAny&lt;string&gt;())).Returns(true);
          mockFileWrapper.Setup(_ =&gt; _.Exists(It.IsAny&lt;string&gt;())).Returns(false);
          mockFileWrapper.Setup(_ =&gt; _.CreateText(logFile.GetAutomationLogsPath() + fileName)).Verifiable();
          //mockFileWrapper.Setup(_ =&gt; _.CreateText(logFile.GetAutomationLogsPath() + fileName)).Returns(new StreamWriter(fileName)).Verifiable();
  
          //act
          logFile.WriteToAutomationLog(fileName, message);
  
          //assert
          mockFileWrapper.Verify(_ =&gt; _.CreateText(logFile.GetAutomationLogsPath() + fileName), Times.Exactly(1));
      }
  </code></pre>
  
  <p>Here is my method I am testing on</p>
  
  <pre><code>public void WriteToAutomationLog(string fileName, string message)
      {
          //Ensure the automation logs path still exists.
          if (_directoryWrapper.Exists(automationLogsPath))
          {
              //Check if file exists
              if (_fileWrapper.Exists(automationLogsPath + fileName))
              {
                  //Append to log file
                  using (StreamWriter sw = _fileWrapper.AppendText(automationLogsPath + fileName))
                  {
  
                  }
              }
              else
              {
                  //Create new file
                  using (StreamWriter sw = _fileWrapper.CreateText(automationLogsPath + fileName))
                  {
                      sw.Write(message);
                  }
              }
          }
      }
  </code></pre>
  
  <p>I have wrappers for the Directory and File class. The issue I am having is when I call sw.Write(message), sw is null in my test. When I use the commented out line of code that returns a StreamWriter, I get an error saying access to the file is denied. However I do not want to actually read the file on the hard drive. How can I go about mocking StreamWriter?</p>
  
  <p>On a side note, if I comment out sw.Write(message), my test passes. This issue came up when I added another test to test sw.Write, so when I added that code my old test broke (the one that I posted).</p>