有什么方法可以断言文本文件已创建吗?

Sta*_*mov -2 c# unit-testing

我想为我的项目编写单元测试,我想知道是否有任何方法可以检查是否在特定目录中创建了任何文件,如果是,则由多少行组成?再次感谢!这是该项目的一些代码。

Dan*_*ann 5

不想在测试过程中创建文件——文件系统属于外部依赖项的类别。如果您与真实的文件系统交互,您的测试将成为集成测试,而不是单元测试。

在这种情况下,您可以做的是通过由接口表示的瘦包装类来协调所有文件系统访问,然后对其进行测试。

例如:

public interface IFileSystem
{
    void WriteAllText(string filePath, string fileContents);    
    bool Exists(string filePath);
}

public class RealFileSystem : IFileSystem
{
    public void WriteAllText(string filePath, string fileContents)
    {
        File.WriteAllText(filePath, fileContents);
    }

    public void Exists(string filePath) 
    {
        return File.Exists(filePath);
    }
}

public class TestFileSystem : IFileSystem
{
    public Dictionary<string, string> fileSystem = new Dictionary<string, string>();
    public void WriteAllText(string filePath, string fileContents)
    {
        fileSystem.Add(filePath, fileContents);
    }
    public void Exists(string filePath) 
    {
        return fileSystem.ContainsKey(filePath);
    }
}
Run Code Online (Sandbox Code Playgroud)