0

Here i have written some lines of code in c# class library to read HTML file content using IO.File code is as below.

 var data = string.Join("", System.IO.File.ReadAllLines("./template1.html"));
 var text= new StringBuilder(data);

Now for the same line of code i need to write test case where i want to mock this IO.File which i am trying to figure out. can anybody help?

Madhav
  • 559
  • 2
  • 11
  • 34
  • 3
    Possible duplicate of [How do you mock out the file system in C# for unit testing?](https://stackoverflow.com/questions/1087351/how-do-you-mock-out-the-file-system-in-c-sharp-for-unit-testing) – ProgrammingLlama Aug 20 '18 at 05:55

1 Answers1

2

If file not very big, mock nothing, create file in test folder, and use it for test.
You, obviously, want extract file name as parameter to your function, so you can load any file in the tests.

public void ProcessDataFromFile(string path)
{
    var data = string.Join("", System.IO.File.ReadAllLines(path));
    var text= new StringBuilder(data);

    // process data
}

In case file is big and makes tests slow - create an abstraction wrapper for reading data, which you can mock in the tests.

public interface IFileReader
{
    string[] ReadAllLinesFrom(string path);
}

In the production code "inject" abstraction to the method where you need read a file

public void ProcessDataFromFile(string path, IFileReader reader)
{
    var data = string.Join("", reader.ReadAllLinesFrom(path));
    var text= new StringBuilder(data);

    // process data
}

For the tests you can create own implementation of IFileReader

public class FakeFileReader : IFileReader
{
    public Dictionary<string, string[]> Files { get; }

    public FakeFileReader ()
    {
        Files = new Dictionary<string, string[]>();
    }

    public string[] ReadAllLinesFrom(string path)
    {
        return Files.GetValueOrDefault(path);
    }        
}

And tests

public void Test()
{
    var fakeReader = new FakeFileReader();
    var path = "pathToSomeFile"
    var data = new[] { "Line 1", "Line 2", Line 3" };
    fakeReader.Files.Add(path, data)

    ProcessDataFromFile(path, fakeReader);

    // Assert
}
Fabio
  • 31,528
  • 4
  • 33
  • 72