【问题标题】:Create a list with specific values with Autofixture C#使用 Autofixture C# 创建具有特定值的列表
【发布时间】:2021-06-13 11:18:10
【问题描述】:

模型具有IdCode 等属性。

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

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

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

提前致谢

【问题讨论】:

  • 您希望序列继续下去(例如“D”、“E”、“F”)还是只需要 4 个具有这些确切代码的模型?
  • 不,我只想要 4 件商品。

标签: c# xunit autofixture


【解决方案1】:

假设您只需要 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; }
}

【讨论】:

  • 感谢您的建议,我会尝试并告诉您
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    相关资源
    最近更新 更多