Skip to content

Instantly share code, notes, and snippets.

@AydinAdn
Last active April 4, 2019 04:04
Show Gist options
  • Save AydinAdn/94e52fb3b8e640876895e26dbe5cf5de to your computer and use it in GitHub Desktop.
Save AydinAdn/94e52fb3b8e640876895e26dbe5cf5de to your computer and use it in GitHub Desktop.
// 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