Last active
April 4, 2019 04:04
-
-
Save AydinAdn/94e52fb3b8e640876895e26dbe5cf5de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/55498470/mocking-streamreader-in-c-sharp-for-unit-test/ | |
public static void Main() | |
{ | |
Mock<IFileManager> mockFileManager = new Mock<IFileManager>(); | |
string fakeFileContents = "Hello world"; | |
byte[] fakeFileBytes = Encoding.UTF8.GetBytes(fakeFileContents); | |
MemoryStream fakeMemoryStream = new MemoryStream(fakeFileBytes); | |
mockFileManager.Setup(fileManager => fileManager.StreamReader(It.IsAny<string>())) | |
.Returns(() => new StreamReader(fakeMemoryStream)); | |
Foo foo = new Foo(mockFileManager.Object); | |
string result = foo.ParseFile("test.txt"); | |
Console.WriteLine(result); | |
} | |
public interface IFileManager | |
{ | |
StreamReader StreamReader(string path); | |
} | |
public class Foo | |
{ | |
IFileManager fileManager; | |
public Foo(IFileManager fileManager) | |
{ | |
this.fileManager = fileManager; | |
} | |
public string ParseFile(string filePath) | |
{ | |
using (var reader = fileManager.StreamReader(filePath)) | |
{ | |
return reader.ReadToEnd(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment