默认情况下,Autofixture 会为属性生成唯一值。因此,您不必指定哪个属性应该是唯一的 - 而是为其他属性指定一个非唯一值:
// with AutoFixture.SeedExtensions
fixture.Build<Foo>().With(f => f.Name, fixture.Create("Name")).CreateMany(20)
请注意,如果您想确保其他属性的值不唯一(只有 Id 唯一),那么您可以为 IPostprocessComposer 创建简单的扩展,为该属性提供一组可能的值:
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 列表,其中只有两个不同的 name 值,以及三个不同的整数属性值:
fixture.Build<Foo>()
.With(f => f.SomeIntegerProperty, 10, 20, 50)
.With(f => f.Name, fixture.CreateMany<string>(2))
.CreateMany(20);