0
我試圖單元測試遞歸表示目錄結構的對象,但即使在最簡單的級別FluentAssertions ShouldBeEquivalentTo
失敗最大遞歸深度達到。FluentAssertions遞歸深度到達與遞歸結構的對象
應該如何寫這個測試來正確地讓測試通過。
此外,如果添加子節點,我如何停止無限重新比較父節點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();
}
樹構建:
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;
}
}
你有超過十級的目錄嗎?你嘗試過'AllowingInfiniteRecursion'選項嗎? – dasblinkenlight
@dasblinkenlight目錄結構可能有10個以上的級別;但對於測試我沒有那麼多。我嘗試了'AllowingInfiniteRecursion',但是這會導致進程最終意外中止(這個測試不應該被需要)。 – Ayb4btu