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

Create a list with specific values with Autofixture C#

该模型具有 IdCode 等属性

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

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

这将导致代码为“A”的所有 4 个数据。我希望这 4 个数据具有代码 "A"、"B"、"C"、"D"

提前致谢

假设您只需要 4 个项目,您可以定义代码集合并使用它使用 LINQ 生成 4 个模型。

public static object[][] Codes =
{
    new object[] { new[] { "A", "B", "C", "D" } }
};

[Theory]
[MemberAutoData(nameof(Codes))]
public void Foo(string[] codes, Fixture fixture)
{
    var builder = fixture.Build<MyModel>(); // Do any other customizations here
    var models = codes.Select(x => builder.With(x => x.Code, x).Create());

    var acutal = models.Select(x => x.Code).ToArray();

    Assert.Equal(codes, acutal);
}

public class MyModel
{
    public int Id { get; set; }
    public string Code { get; set; }
}

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

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);

输出

[
  {Code: "A"},
  {Code: "B"},
  {Code: "C"},
  {Code: "D"}
]

如果您想要倒序的结果,请使用 Stack 而不是 QueuePop 而不是 Dequeue

扩展方法似乎已经成熟:

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);