【问题标题】:How to I mock System.IO.File.ReadAllLines("./abc.html") in unit test code written c#如何在 C# 编写的单元测试代码中模拟 System.IO.File.ReadAllLines("./abc.html")
【发布时间】:2018-08-20 05:51:18
【问题描述】:

这里我在 c# 类库中编写了几行代码来使用 IO.File 读取 HTML 文件内容 代码如下。

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

现在对于同一行代码,我需要编写测试用例,我想在其中模拟我试图弄清楚的 IO.File。 有人可以帮忙吗?

【问题讨论】:

标签: c# unit-testing tdd


【解决方案1】:

如果文件不是很大,不做任何模拟,在测试文件夹中创建文件,并使用它进行测试。
显然,您希望提取文件名作为函数的参数,因此您可以在测试中加载任何文件。

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 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
}

【讨论】:

  • 为什么不用TextReader?
猜你喜欢
  • 2013-06-02
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多