I am exploring using AutoFixture
to handle creating some of our test data for unit tests. So far, it looks like this will save us quite a bit of code/maintenance. My only issue right now is that when creating an object, the complex children objects on it will not have the IDs hooked up appropriately. I'm trying to find a way to gracefully overcome this instead of just manually hooking up the IDs after the object is created. See example below:
public class Bar
{
public int Id {get; set;}
public string Name {get; set;}
public Foo Foo {get; set;}
public int FooId {get; set;}
}
public class Foo
{
public int Id {get; set}
public string Description {get; set;}
}
In this example, calling var myBar = myFixture.Create<Bar>()
will populate all of the properties for both Bar
and it's child property Foo
. My issue here is that myBar.FooId
will be different than the value for myBar.Foo.Id
. The same issue exists for creating child collections. How can I overcome this without manually hooking up all of my IDs?
Can you try this :
var obj = myFixture
.Build<Bar>()
.Without(b => b.Foo)
.Without(b => b.FooId)
.Do(b =>
{
b.Foo = fixture.Create<Foo>();
b.FooId = fixture.Create<int>();
b.Foo.Id = b.FooId;
})
.Create()
Or you can check this 3rd package which support the initialization of the navigation properties in EF for AutoFixture
When the interceptor creates a new navigation object, it will check for a matching int ____Id property. If present, it will set the Id property of the new object so that foo.BarId == foo.Bar.Id. This also applies when the name of the table is included in the Id property, so foo.BarId == foo.Bar.BarId.