Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 765
AsValeO Avatar asked Nov 23 '15 11:11

AsValeO


1 Answers

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.

like image 171
Enrico Campidoglio Avatar answered Nov 06 '22 08:11

Enrico Campidoglio