Create an EF object stub using AutoFixture

For example, I have these partial classes that were created by EF Database First:

Dog: (object EF)

public partial class Dog { public int DogID { get; set; } public string Name { get; set; } public int Age { get; set; } public int PetOwnerID { get; set; } // Navigation property public virtual PetOwner PetOwner { get; set; } } 

PetOwner: (object EF)

 public partial class PetOwner { public int PetOwnerID { get; set; } public string PetOwnerName { get; set; } // Navigation property public virtual ICollection<Dog> Dogs { get; set; } } 

I need a simple stub like Dog for unit testing. But when I try to create a stub using AutoFixture, a recursive dependency exception is thrown. If I try to change the behavior of a device like this, it freezes.

 var fixture = new Fixture(); fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => fixture.Behaviors.Remove(b)); fixture.Behaviors.Add(new OmitOnRecursionBehavior(1)); var dog = fixture.Create<Dog>(); 

I don't need any EF functions, just a simple class with properties for testing. I have NUnit, Moq, AutoFixture.

UPDATE:

 var dog = fixture.Build<Dog>().Without(x => x.PetOwner).Create(); 

This solves the problem, but I need the navigation property not to be null.

+5
source share
1 answer

I could not reproduce the error. This test passes just fine using AutoFixture 3.36.12 :

 [Test] public void CreateEntityWithNavigationProperty() { var fixture = new Fixture(); fixture.Behaviors.Add(new OmitOnRecursionBehavior()); var dog = fixture.Create<Dog>(); Assert.That(dog.PetOwner, Is.Not.Null); Assert.That(dog.PetOwner.Dogs, Is.Empty); } 

However, as a workaround, you can explicitly configure AutoFixture to create objects of type PetOwner without populating the PetOwner.Dogs property:

 [Test] public void CreateEntityWithNavigationProperty() { var fixture = new Fixture(); fixture.Customize<PetOwner>(c => c.With(owner => owner.Dogs, Enumerable.Empty<Dog>())); var dog = fixture.Create<Dog>(); Assert.That(dog.PetOwner, Is.Not.Null); Assert.That(dog.PetOwner.Dogs, Is.Empty); } 

This gives the same result as the previous test, where the PetOwner.Dogs property PetOwner.Dogs set to an empty sequence, which is much better than null .

+4
source

Source: https://habr.com/ru/post/1236608/


All Articles