dimanche 31 juillet 2016

FluentAssertions Recursion Depth Reached in object with recursive structure

I'm trying to unit test an object that recursively represents a directory structure, but even at the simplest level the fluentAssertions ShouldBeEquivalentTo is failing with The maximum recursion depth was reached.

How should this test be written to correctly get the test to pass.

Additionally, if child nodes were added, how do I stop the ShouldBeEquivalentTo infinitely re-comparing the parent DirectoryNode?

Here is the code, it is using Xunit, FluentAssertions and System.IO.Abstractions libraries.

The test:

[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 properties class:

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

Tree Builder:

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

Aucun commentaire:

Enregistrer un commentaire