AsValeO
AsValeO

Reputation: 3039

Create an EF entity stub with AutoFixture

For example I've got these partial classes that was generated by EF Database First:

Dog: (EF entity)

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: (EF entity)

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 of Dog type for unit testing. But when I try to generate a stub using AutoFixture a recursive dependency exception throws. If I try to change fixture behavior like this, it hangs on.

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 functionality here, just a simple class with a properties to test. I've got NUnit, Moq, AutoFixture.

UPDATE:

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

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

Upvotes: 8

Views: 3895

Answers (1)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

I wasn't able to 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 customize 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 yields the same result as the previous test, where the PetOwner.Dogs property is set to an empty sequence, which is much better than null.

Upvotes: 7

Related Questions