Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Last active March 25, 2024 08:33
Show Gist options
  • Save MikeMKH/b16352ebcafb4f480f5b to your computer and use it in GitHub Desktop.
Save MikeMKH/b16352ebcafb4f480f5b to your computer and use it in GitHub Desktop.
How to live with a circular reference with AutoFixture
[TestInitialize]
public void BeforeEach()
{
_fixture = new Fixture();
// client has a circular reference from AutoFixture point of view
_fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
_fixture.Behaviors.Add(new OmitOnRecursionBehavior());
}
@flier268
Copy link

Thanks for Mike

internal static class IFixtureExtensions
  {
      public static IFixture FixCircularReference(this IFixture fixture)
      {
          fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
          fixture.Behaviors.Add(new OmitOnRecursionBehavior());
          return fixture;
      }
  }

@Broderick-Westrope
Copy link

Life saver, thanks Mike!

@Tridy
Copy link

Tridy commented Jul 25, 2023

Maybe not exactly the same thing, but I got here when was searching for a circular reference problem when using Entity Framework. In my case, some entities have circular references and to eliminate the problem with them while using AutoFixture I used .Without method so it would skip those properties:

Asset[] assets = fixture.Build<Asset>()
 .With(x => x.AssetId, 45)
   .Without(x => x.Sensors)
   .Without(x => x.Device)
   .Without(x => x.Project)
 .CreateMany(15)
 .ToArray();

@MikeMKH
Copy link
Author

MikeMKH commented Jul 28, 2023

@Tridy different, very clever solution to the EF problem, thank you for adding it.

@holbizmetrics
Copy link

holbizmetrics commented Mar 25, 2024

What sometimes also might help is to use:

_fixture = new Fixture();
// client has a circular reference from AutoFixture point of view
_fixture.OmitAutoProperties = true;

P.S.: In case of some properties causing the problem, especially if they may not be needed to initialize the object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment