Last active
March 25, 2024 08:33
-
-
Save MikeMKH/b16352ebcafb4f480f5b to your computer and use it in GitHub Desktop.
How to live with a circular reference with AutoFixture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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()); | |
} |
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;
}
}
Life saver, thanks Mike!
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();
@Tridy different, very clever solution to the EF problem, thank you for adding it.
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
Thanks man this worked!