Search code examples
c#xunitautofixture

Create a list with specific values with Autofixture C#


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


Solution

  • 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; }
    }