具有独特 属性 的 AutoFixture 构建集合

AutoFixture build collection with unique property

是否有可能在 AutoFixture 中创建具有唯一 属性 的集合?例如,我想创建一个集合:

public class Foo {
 public int Id {get; set;}
 public string Name {get;set;}
}

具有独特性 Id。它看起来像这样:

var fixture = new Fixture();

fixture
 .Build<Foo>()
 .WithUnique((foo) => foo.Id)
 .CreateMany(20);

我知道可以通过定制来做到这一点,但我认为这是很常见的情况,所以可能 AutoFixture 已经准备好了吗?

Autofixture 默认生成唯一的属性值。因此,您不必指定哪个 属性 应该是唯一的 - 相反,为其他 属性:

指定一个非唯一值
// with AutoFixture.SeedExtensions
fixture.Build<Foo>().With(f => f.Name, fixture.Create("Name")).CreateMany(20)

请注意,如果您想确保其他属性的值不唯一(只有 Id 唯一),那么您可以为 IPostprocessComposer 创建简单的扩展,为 [=21= 提供一组可能的值]:

public static IPostprocessComposer<T> With<T, TProperty>(
    this IPostprocessComposer<T> composer,
    Expression<Func<T, TProperty>> propertyPicker,
    IEnumerable<TProperty> possibleValues) =>
      composer.With(propertyPicker, possibleValues.ToArray());

public static IPostprocessComposer<T> With<T, TProperty>(
    this IPostprocessComposer<T> composer,
    Expression<Func<T, TProperty>> propertyPicker,
    params TProperty[] possibleValues)
{
    var rnd = new Random();
    return composer.With(
       propertyPicker,
       () => possibleValues[rnd.Next(0, possibleValues.Length)]);
}

用法很简单——下面的代码创建了 foos 列表,其中只有两个不同的名称值,以及三个不同的整数值 属性:

fixture.Build<Foo>()
    .With(f => f.SomeIntegerProperty, 10, 20, 50)
    .With(f => f.Name, fixture.CreateMany<string>(2))
    .CreateMany(20);