具有复杂子属性的 .NET AutoFixture
.NET AutoFixture with complex child properties
我正在探索使用 AutoFixture
来处理为单元测试创建一些测试数据。到目前为止,看起来这将为我们节省不少 code/maintenance。我现在唯一的问题是,在创建对象时,其上的复杂子对象不会正确连接 ID。我试图找到一种方法来优雅地克服这个问题,而不是在创建对象后手动连接 ID。请参见下面的示例:
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;}
}
在此示例中,调用 var myBar = myFixture.Create<Bar>()
将填充 Bar
及其子项 属性 Foo
的所有属性。我的问题是 myBar.FooId
与 myBar.Foo.Id
的值不同。创建子集合也存在同样的问题。如果不手动连接我的所有 ID,我该如何克服这个问题?
你能试试这个吗:
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()
或者您可以查看此 3rd package,它支持在 EF 中为 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.
我正在探索使用 AutoFixture
来处理为单元测试创建一些测试数据。到目前为止,看起来这将为我们节省不少 code/maintenance。我现在唯一的问题是,在创建对象时,其上的复杂子对象不会正确连接 ID。我试图找到一种方法来优雅地克服这个问题,而不是在创建对象后手动连接 ID。请参见下面的示例:
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;}
}
在此示例中,调用 var myBar = myFixture.Create<Bar>()
将填充 Bar
及其子项 属性 Foo
的所有属性。我的问题是 myBar.FooId
与 myBar.Foo.Id
的值不同。创建子集合也存在同样的问题。如果不手动连接我的所有 ID,我该如何克服这个问题?
你能试试这个吗:
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()
或者您可以查看此 3rd package,它支持在 EF 中为 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.