FluentAssesss递归结构的对象中达到的递归深度



我试图对一个递归表示目录结构的对象进行单元测试,但即使在最简单的级别上,fluentAssertions ShouldBeEquivalentTo也会因而失败。已达到最大递归深度

这个测试应该如何编写才能正确地通过测试。

此外,如果添加了子节点,如何停止ShouldBeEquivalentTo无限地重新比较父DirectoryNode

这是代码,它使用XunitFluentAssertionsSystem.IO.Abstractions库。

测试:

[Fact]
public void DirectoryTreeBuilder_BuildTree_String_TopNodeTest()
{
    // Arrange
    string path = "C:\";
    var mockFileSystem = new MockFileSystem();
    mockFileSystem.AddDirectory(path);
    var expected = new DirectoryNode
    {
        Info = mockFileSystem.DirectoryInfo.FromDirectoryName(path),
        Children = new List<DirectoryNode>()
    };
    // Act
    var builder = new DirectoryTreeBuilder(mockFileSystem);
    var calculated = builder.BuildTree(path);
    // Assert
    calculated.ShouldBeEquivalentTo(expected);
}

DirectoryNode属性类:

public class DirectoryNode
{
    public DirectoryNode Parent { get; set; }
    public DirectoryInfoBase Info { get; set; }
    public List<DirectoryNode> Children { get; set; }
    public List<FileInfoBase> Files => Info.GetFiles().ToList();
}

树生成器:

public class DirectoryTreeBuilder
{
    private readonly IFileSystem fileSystem;
    public DirectoryTreeBuilder(IFileSystem fileSystem)
    {
        this.fileSystem = fileSystem;
    }
    public DirectoryTreeBuilder() : this(new FileSystem())
    {
    }
    public DirectoryNode BuildTree(string path)
    {
        var directoryInfo = fileSystem.DirectoryInfo.FromDirectoryName(path);
        return BuildTree(directoryInfo);
    }
    public DirectoryNode BuildTree(DirectoryInfoBase directoryInfo)
    {
        var node = new DirectoryNode
        {
            Info = directoryInfo,
        };
        var directories = directoryInfo.GetDirectories();
        var children = new List<DirectoryNode>();
        // Process list of child directories
        foreach (var directory in directories)
        {
            var child = BuildTree(directory);
            child.Parent = node;
            children.Add(child);
        }
        node.Children = children;
        return node;
    }
}

我发现了问题,DirectoryNode.Info属性包含一个DirectoryInfoBase,它只是DirectoryInfo对象的包装器。

DirectoryInfo具有属性Root,该属性在最高级别(如C:\)将仅返回自身。这是FluentAssessments ShouldBeEquivalentTo递归失败的元素。

不幸的是,ShouldBeEquivalentTo似乎不能忽略子属性。

相关内容

  • 没有找到相关文章

最新更新