Circular references

Handle parent-child graphs that reference each other using OmitOnRecursionBehavior.

By default AutoFixture throws when it detects a circular object graph.

Example scenario

TreeNode has a Parent property that points back to another node. A plain Create<TreeNode>() triggers infinite recursion detection.

Example

Default behavior throws:

var fixture = new Fixture();

Assert.ThrowsAny<ObjectCreationException>(() => fixture.Create<TreeNode>());

Replace the default throwing behavior to omit recursive properties:

fixture.Behaviors
    .OfType<ThrowingRecursionBehavior>()
    .ToList()
    .ForEach(b => fixture.Behaviors.Remove(b));
fixture.Behaviors.Add(new OmitOnRecursionBehavior());

var node = fixture.Create<TreeNode>();

Assert.NotNull(node);

How it works

  • ThrowingRecursionBehavior — default; fails fast on cycles
  • OmitOnRecursionBehavior — stops recursion and leaves the recursive property unset
  • Remove the throwing behavior before adding the omit behavior

See also Behaviors.

Next steps

API