如何使用AutoFixture基于父级的属性分配子对象的属性?

时间:2013-03-05 16:31:24

标签: autofixture

我有一个Order对象,其中包含Shipments个集合。 Shipment有一个名为OrderId的属性。如何自定义AutoFixture以生成order.Shipments.All(s => s.OrderId == order.Id)为真的订单?

Class diagram

我已经尝试过以下技术但没有成功:

fixture.Customize<Order>(c => c.Do(o => {
    // This is called before the Order's properties have been populated,
    // so there are no shipments yet.
    foreach (var s in o.Shipments) {
        s.OrderId = o.Id;
    }
}));

fixture.Customize<Order>(c => c.Do(o => {
    o.Id = c.Create<Guid>();       // System.InvalidCastException
    o.Shipments = new List<Shipment>(c.CreateMany<Shipment>());
    foreach (var shipment in o.Shipments) {
        shipment.OrderId = o.Id;
    }
}));

class OrderGenerator : ISpecimenBuilder {
    public object Create(object request, ISpecimenContext context) {
        if (request as Type == typeof(Order)) {
            // ObjectCreationException due to circular reference
            var order = (Order)context.Resolve(request);
            foreach (var shipment in order.Shipments) {
                shipment.OrderId = order.Id;
            }
        }
    }
}
fixture.Customizations.Add(new OrderGenerator());

最好的方法是什么?

0 个答案:

没有答案