gpt4 book ai didi

c# - 使用 Autofixture 将子实例的属性值设置为固定值

转载 作者:IT王子 更新时间:2023-10-29 04:43:34 24 4
gpt4 key购买 nike

在使用 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 实例而不是 Address 实例上的 City 属性。

有什么建议吗?

是的,我知道我可以像下面这样添加一个额外的步骤:

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

最佳答案

为了完整起见,这里有另一种方法:

fixture.Customize<Address>(c => 
c.With(addr => addr.City, "foo"));

var person = fixture.Create<Person>();

这将自定义 Address 的所有实例的创建

如果您最终经常使用它,那么将它包装在 ICustomization 中可能是值得的:

public class AddressConventions : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<Address>(c =>
c.With(addr => addr.City, "foo"));
}
}

fixture.Customize(new AddressConventions());

关于c# - 使用 Autofixture 将子实例的属性值设置为固定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com