我正在尝试对递归表示目录结构的对象进行单元测试,但即使在最简单的级别,fluentAssertions ShouldBeEquivalentTo
也会失败并且达到了最大递归深度。 / p>
如何编写此测试以正确地通过测试。
此外,如果添加了子节点,如何阻止ShouldBeEquivalentTo
无限重新比较父DirectoryNode
?
以下是代码,它使用的是Xunit
,FluentAssertions
和System.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();
}
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;
}
}
答案 0 :(得分:0)
我发现了这个问题,DirectoryInfo
属性包含DirectoryInfo
,它只是Root
对象的包装。
ShouldBeEquivalentTo
具有属性ShouldBeEquivalentTo
,在最高级别(例如C:\)将返回自身。这是FluentAssertions <pre>
递归失败的元素。
不幸的是,<html>
<body>
<pre>
plain text sith spaces and newlines
</pre>
</html>
似乎无法忽略子属性。