我有一个Order
对象,其中包含Shipments
个集合。 Shipment
有一个名为OrderId
的属性。如何自定义AutoFixture以生成order.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());
最好的方法是什么?