1

我有一个有集合的Order对象。有一个名为 的属性。如何自定义 AutoFixture 以生成正确的订单?ShipmentsShipmentOrderIdorder.Shipments.All(s => s.OrderId == order.Id)

类图

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

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());

做这个的最好方式是什么?

4

0 回答 0