Advertisement
pszczyg

MockingFileSystem_2

Jun 2nd, 2021
1,215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1.     public interface IFileSystemInteractor
  2.     {
  3.         StreamReader OpenText(string inputFilePath);
  4.         StreamWriter AppendText(string outputFilePath);
  5.     }
  6.  
  7.     public class FileSystemInteractor : IFileSystemInteractor
  8.     {
  9.         public StreamReader OpenText(string inputFilePath)
  10.         {
  11.             return File.OpenText(inputFilePath);
  12.         }
  13.  
  14.         public StreamWriter AppendText(string outputFilePath)
  15.         {
  16.             return File.AppendText(outputFilePath);
  17.         }
  18.     }
  19.  
  20.     public class FileSystemInteractorMock : IFileSystemInteractor
  21.     {
  22.         private readonly MemoryStream _inputMemoryStream;
  23.         public MemoryStream OutputMemoryStream { get; }
  24.  
  25.         public FileSystemInteractorMock(string fileContent)
  26.         {
  27.             _inputMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(fileContent));
  28.             OutputMemoryStream = new MemoryStream();
  29.         }
  30.        
  31.         public StreamReader OpenText(string inputFilePath)
  32.         {
  33.             var streamReader = new StreamReader(_inputMemoryStream);
  34.             return streamReader;
  35.         }
  36.  
  37.         public StreamWriter AppendText(string outputFilePath)
  38.         {
  39.             var streamWriter = new StreamWriter(OutputMemoryStream);
  40.             return streamWriter;
  41.         }
  42.     }
  43.  
  44.     [TestFixture]
  45.     public class Tests
  46.     {      
  47.         [Test]
  48.         public void Examined_Data_Written_Correctly_To_File()
  49.         {
  50.             var inputFilePath = "inputFile.txt";
  51.             var outputFilePath = "outputFile.txt";
  52.             var inputFileContents = string.Join(Environment.NewLine, new[] {"OK", "WRONG", "OK", "WRONG"});
  53.  
  54.             var fileInteractorMock = new FileSystemInteractorMock(inputFileContents);
  55.             var sut = new ProductionClass(fileInteractorMock);
  56.             var resultAsync = sut.CheckDataAndStoreResultsAsync(inputFilePath, outputFilePath);
  57.             resultAsync.Wait();
  58.  
  59.             var outputLines = Encoding.UTF8.GetString(fileInteractorMock.OutputMemoryStream.ToArray())
  60.                 .Split(new [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
  61.             CollectionAssert.AreEquivalent(new []{"1", "3"}, outputLines, $"Actual:{string.Join(",", outputLines)}");
  62.         }
  63.     }
  64.  
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement