Autofixture - 在 属性 的新列表中基于先前构建的 属性

Autofixture - base property in new list on property from a previously constructed one

我想我遗漏了什么,但我想做的是:

我的 C# 代码中有两个数据库实体。一个是另一个的 child,因此 child 包含一个应引用 parent 的 ID 的字段。

parentclass如下

public class Product
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }

    public decimal DeliveryPrice { get; set; }
}

childclass如下:

public class ProductOption
{
    public Guid Id { get; set; }

    public Guid ProductId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

我创建了一个随机 "parents" 列表:

var products = fixture.CreateMany<Product>(5).ToList();

然后我想做的是创建 10 个 child objects,并从 AutoFixture 创建的产品列表中随机给他们一个 ProductId。所以我尝试了这个:

var rand = new Random();
var options = fixture.Build<ProductOption>()
    .With(option => option.ProductId, products[rand.Next(0, 5)].Id)
    .CreateMany(10)
    .ToList();

几乎 有效,但我发现所有 ProductId 都是同一个,所以它显然只命中 rand.Next 一次.

我在做的是什至possible/advisable吗?

当我为 属性 提供值时,我希望使用相同 builder/fixture 构建的所有实例都提供值。
所以你注意到的是期望的行为。

您可以提供 "factory" 而不是已经生成的值,它将在实例创建期间为 属性 生成值。
最新的 Autofixture 版本为接受函数作为参数的 .With 方法引入了重载。

var rand = new Random();
Func<Guid> pickProductId = () => products[rand.Next(0, 5)].Id;

var options = 
    fixture.Build<ProductOption>()
           .With(option => option.ProductId, pickProductId)
           .CreateMany(10)
           .ToList();

// Prove
options.Select(o => o.ProductId).ToHashSet().Should().HaveCountGreaterThan(1); // Pass Ok