在使用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; }
}
我希望将地址实例的城市属性赋予特定值。我在考虑这个测试代码: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。