C# 如何在c编写的单元测试代码中模拟System.IO.File.ReadAllLines(";/abc.html";)#

C# 如何在c编写的单元测试代码中模拟System.IO.File.ReadAllLines(";/abc.html";)#,c#,unit-testing,tdd,C#,Unit Testing,Tdd,在这里,我在c#类库中编写了几行代码,使用IO.file 代码如下 var data = string.Join("", System.IO.File.ReadAllLines("./template1.html")); var text= new StringBuilder(data); 现在,对于同一行代码,我需要编写一个测试用例,在这个测试用例中,我要模拟我试图弄明白的IO.File。 有人能帮忙吗?如果文件不是很大,什么都不模拟,在测试文件夹中创建文件,并将其用于测试。 显然,您希

在这里,我在c#类库中编写了几行代码,使用IO.file 代码如下

 var data = string.Join("", System.IO.File.ReadAllLines("./template1.html"));
 var text= new StringBuilder(data);
现在,对于同一行代码,我需要编写一个测试用例,在这个测试用例中,我要模拟我试图弄明白的IO.File
有人能帮忙吗?

如果文件不是很大,什么都不模拟,在测试文件夹中创建文件,并将其用于测试。
显然,您希望将文件名提取为函数的参数,以便可以加载测试中的任何文件

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

    // process data
}
如果文件太大,使测试速度变慢,那么创建一个抽象包装器来读取数据,您可以在测试中模拟它

public interface IFileReader
{
    string[] ReadAllLinesFrom(string path);
}
在生产代码中,向需要读取文件的方法“注入”抽象

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

    // process data
}
对于测试,您可以创建自己的
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);
    }        
}

如果文件不是很大,则不模拟任何内容,在测试文件夹中创建文件,并将其用于测试。
显然,您希望将文件名提取为函数的参数,以便可以加载测试中的任何文件

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

    // process data
}
如果文件太大,使测试速度变慢,那么创建一个抽象包装器来读取数据,您可以在测试中模拟它

public interface IFileReader
{
    string[] ReadAllLinesFrom(string path);
}
在生产代码中,向需要读取文件的方法“注入”抽象

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

    // process data
}
对于测试,您可以创建自己的
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);
    }        
}

为什么不使用TextReader?为什么不使用TextReader?