Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Last active March 25, 2024 08:33
Show Gist options
  • Select an option

  • Save MikeMKH/b16352ebcafb4f480f5b to your computer and use it in GitHub Desktop.

Select an option

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());
}
@Broderick-Westrope

Copy link
Copy Markdown

Life saver, thanks Mike!

@Tridy

Tridy commented Jul 25, 2023

Copy link
Copy Markdown

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

MikeMKH commented Jul 28, 2023

Copy link
Copy Markdown
Author

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

@holbizmetrics

holbizmetrics commented Mar 25, 2024

Copy link
Copy Markdown

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