使用 Autofixture C# 创建具有特定值的列表

Adr*_*rma 1 c# xunit autofixture

该模型具有属性等IdCode

我想用特定的不同代码创建 4 个数据。

 var data = _fixture.Build<MyModel>()
                .With(f => f.Code, "A")
                .CreateMany(4);
Run Code Online (Sandbox Code Playgroud)

这将产生所有 4 个数据均带有代码“A”。我想要 4 个数据的代码为“A”、“B”、“C”、“D”

提前致谢

Shi*_*ljo 15

有一个更简单的方法可以做到这一点

string[] alphabets = { "A", "B", "C", "D" };
var queue = new Queue<string>(alphabets);

var data = _fixture.Build<MyModel>()
               .With(f => f.Code, () => queue.Dequeue())
               .CreateMany(alphabets.Length);
Run Code Online (Sandbox Code Playgroud)

输出

[
  {Code: "A"},
  {Code: "B"},
  {Code: "C"},
  {Code: "D"}
]
Run Code Online (Sandbox Code Playgroud)

如果您想要相反顺序的结果,请使用Stack代替QueuePop代替Dequeue


Dar*_*ryl 6

这对于扩展方法来说似乎已经成熟:

public static IPostprocessComposer<T> WithValues<T, TProperty>(this IPostprocessComposer<T> composer,
        Expression<Func<T, TProperty>> propertyPicker,
        params TProperty[] values)
{
    var queue = new Queue<TProperty>(values);

    return composer.With(propertyPicker, () => queue.Dequeue());
}

// Usage:
var data = _fixture.Build<MyModel>()
           .WithValues(f => f.Code, "A", "B", "C", "D")
           .CreateMany(4);
Run Code Online (Sandbox Code Playgroud)