【发布时间】:2015-03-05 02:26:17
【问题描述】:
是否可以在使用 Autofixture 构建父级时为子实例上的属性分配固定值?它会像魅力一样为子实例上的所有属性添加默认值,但我想覆盖并为子实例上的某个属性分配一个特定值。
鉴于这种父/子关系:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public int Number { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
我想为地址实例上的 City 属性分配一个特定值。我在想这个测试代码的行:
var fixture = new Fixture();
var expectedCity = "foo";
var person = fixture
.Build<Person>()
.With(x => x.Address.City, expectedCity)
.Create();
Assert.AreEqual(expectedCity, person.Address.City);
这是不可能的。我猜是反射异常
System.Reflection.TargetException : Object does not match target type.
...Autofixture 尝试将值分配给 Person 实例上的 City 属性,而不是 Address 实例。
有什么建议吗?
是的,我知道我可以添加一个额外的步骤,如下所示:
var fixture = new Fixture();
var expectedCity = "foo";
// extra step begin
var address = fixture
.Build<Address>()
.With(x => x.City, expectedCity)
.Create();
// extra step end
var person = fixture
.Build<Person>()
.With(x => x.Address, address)
.Create();
Assert.AreEqual(expectedCity, person.Address.City);
...但希望有第一个版本或类似的东西(步骤更少,更简洁)。
注意:我使用的是 Autofixture v3.22.0
【问题讨论】:
标签: c# hierarchy autofixture