在 AutoFixture 中根据另一个设置 属性

Setting one property based on another in AutoFixture

我正在尝试使用 AutoFixture 创建夹具,其中对象的一个​​ 属性 与另一个相关,并且其中一个属性是作为夹具的一部分创建的。

我目前拥有的是:

fixture = new Fixture().Customize(new MultipleCustomization());
Object object;
double constant;
object = fixture.Build<Object>()
                .With(o => o.PropertyOne, fixture.Create<double>)
                .With(o => o.PropertyTwo, constant * o.PropertyOne)
                .Create());

这行不通,因为 "The name 'o' does not exist in the current context",这是有道理的。

有没有办法在创建夹具的过程中做到这一点?

我的情况有点复杂,因为我实际上是在生成一个列表,所以代码看起来像:

fixture = new Fixture().Customize(new MultipleCustomization());
List<Object> objectListFixture;
double constant;
objectListFixture.AddRange(
    fixture.Build<Object>()
           .With(o => o.PropertyOne, fixture.Create<double>)
           .With(o => o.PropertyTwo, constant * o.PropertyOne)
           .CreateMany());

如果可能的话,我真的很想避免 for 循环。

像这样应该可以做到,尽管您可能需要先填充 o.PropertyOne:

var fixture = new Fixture();
var objs = fixture
    .Build<MyObject>()
    .Without(o => o.PropertyOne)
    .Without(o => o.PropertyTwo)
    .Do(o =>
        {
            o.PropertyOne = fixture.Create<double>();
            o.PropertyTwo = o.PropertyOne;
        })
    .CreateMany()
    .ToList();

但是,如果 PropertyTwo 依赖于 PropertyOne,作为对象设计的一部分实施该规则不是更好吗?