I have an Order
object that has a Shipments
collection. Shipment
has a property called OrderId
. How can I customize AutoFixture to generate an order where order.Shipments.All(s => s.OrderId == order.Id)
is true?
I've tried the following techniques already with no success:
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());
What is the best way to do this?