我正在使用Bogus生成测试数据,但我有一些字段依赖于另一个对象的部分(我希望为每一代随机选择)但必须彼此一致。
这可能不是最好的解释,所以希望这个例子能更好地解释它。
我有一个Order
包含来自Customer
.
public class Customer
{
public Guid Id { get; set; }
public string Currency { get; set; }
}
public class Order
{
public Guid Id { get; set; }
public Guid CustomerId { get; set; } // The ID of a customer
public string Currency { get; set; } // The currency for the customer identified by CustomerId
public decimal Amount { get; set; }
}
我可以使用以下方法生成一些客户:
var customerFaker =
new Faker<Customer>()
.StrictMode(true)
.RuleFor("Id", f => f.Random.Guid())
.RuleFor("Id", f => f.Finance.Currency());
var customers = customerFaker.Generate(10);
但是当涉及到“共享”在订单生成器中的规则之间选择的客户时,我陷入了困境:
var orderFaker =
new Faker<Order>()
.StrictMode(true)
.RuleFor("Id", f => f.Random.Guid())
.RuleFor("Amount", f => f.Finance.Amount())
.RuleFor("CustomerId", f => f.PickRandom(customers).Id)
//How do I share the Customer that's been chosen to use it in the rule below?
.RuleFor("Currency", f => f.PickRandom(customers).Currency);
我想出了一些不太理想的方法(比如每次都实例化一个新的 Faker 并传入一个随机的客户),但我正在处理非常复杂的对象和依赖项,所以我想避免如果可能的话。
我目前的想法是,最好的方法可能是扩展Order
类以能够存储Customer
,然后再将其转换为订单。考虑到我需要这样做的模型数量,如果可能的话,我想避免这种情况。
public class OrderWithCustomer : Order
{
public Customer Customer { get; set; }
}
var orderWithCustomerFaker =
new Faker<OrderWithCustomer>()
.StrictMode(true)
.RuleFor("Id", f => f.Random.Guid())
.RuleFor("Amount", f => f.Finance.Amount())
.RuleFor("Customer", f => f.PickRandom(customers))
.RuleFor("CustomerId", (f, o) => o.Customer.Id)
.RuleFor("Currency", (f, o) => o.Customer.Currency);
var orders =
orderWithCustomerFaker
.Generate(10)
.Select(withCustomer => (Order)withCustomer);