AutoFixture可以被深度和圆形的对象图淹没

Kei*_*oom 7 c# autofixture

我正在使用的域模型有很多循环引用.实际上,可以从图中的任何点获取大多数对象.许多这些循环引用也在集合中.因此,一个Booking集合的集合中Students有一个集合,Courses其中包含Bookings等等.这不是真正的模型,只是一个例子.问题是由大约30个不同类别的组合引起的.

要使用此模型,我正在配置和使用AutoFixture

var fixture = new Fixture().Customize(new MultipleCustomization());
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors.Add(new OmitOnRecursionBehavior());

var booking = fixture.CreateAnonymous<Booking>();
Run Code Online (Sandbox Code Playgroud)

这会导致AutoFixture运行大约20分钟,直到它最终因OutOfMemoryException而失败.

这个模型是否要求AutoFixture创建一个永无止境的无限图?如果是这样,我有什么办法可以配置它来限制图表的深度吗?

Mag*_*nus 0

我意识到这是一个老问题,但对于发现这个问题的任何人来说,我认为 的行为OmitOnRecursionBehaviour可能已经改变(或已修复:-)。默认递归深度为 1。

并且您可以指定recursionDepth。如果设置得太深,则会导致 StackOverflowException,而不是 OutOfMemoryException,至少对我来说是这样。

无论如何,这是一个简单的例子。

void Main()
{   
    var fixture = new Fixture();
    fixture
        .Behaviors
        .OfType<ThrowingRecursionBehavior>()
        .ToList()
        .ForEach(b => fixture.Behaviors.Remove(b));
        
    fixture.Behaviors.Add(new OmitOnRecursionBehavior(10));
    var node = fixture.Create<Node>();      
    
    Console.WriteLine($"It goes {HowDeepDoesItGo(node)} levels down");  
    // Outputs:
    //     It goes 10 levels down
    // With OmitOnRecursionBehavior(), without the recursionDepth argument, then outputs:
    //     It goes 1 levels down
}

int HowDeepDoesItGo(Node node, int level = 1)
{
    if (node.Link is null) return level;
    return HowDeepDoesItGo(node.Link, level + 1);
}

public class Node
{   
    public Node Link { get; init;}
}
Run Code Online (Sandbox Code Playgroud)