1

The Model has properties Id, Code etc.

I want to create 4 data with specific different codes.

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

This results in all 4 data with Code "A". I want the 4 data to have codes "A", "B", "C", "D"

Thanks in Advance

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79

3 Answers3

11

There is an easier way to do this

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

Output

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

In case if you want the result in reverse order use Stack instead of Queue and Pop instead of Dequeue

Shiljo Paulson
  • 518
  • 7
  • 17
5

This seems ripe for an extension method:

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);
Daryl
  • 18,592
  • 9
  • 78
  • 145
4

Assuming you only need 4 items you can define your collection of codes and use it to generate the 4 models using LINQ.

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; }
}
Andrei Ivascu
  • 1,172
  • 8
  • 17