有没有办法断言是否创建了文本文件?

时间:2014-07-07 17:02:55

标签: c# unit-testing

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

3 个答案:

答案 0 :(得分:4)

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

在这种情况下,您可以通过界面表示的瘦包装类调解所有文件系统访问,然后对其进行测试。

例如:

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

答案 1 :(得分:3)

要查看文件是否存在,请使用File.Exists()

string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

要查看文件中有多少行,请计算File.ReadLines()的迭代次数(每this answer):

var lineCount = File.ReadLines(@"C:\file.txt").Count();

答案 2 :(得分:0)

您可能只想在测试结束时坚持使用if语句

if (File.Exists("file/path") && File.ReadLines("file/path").Count() 
    == your_number_of_lines)
{
    //passed!
}
相关问题