CreateMany generates null values when using partially filled objects in a With clause

63 Views Asked by At

Having the code below, I'm generating 2 student objects using CreateMany(2). Country must be "England" for both objects. The other SchoolId must be unique.

But the students variable below contains School objects with null as SchoolId, while I expect unique values there. What am I doing wrong? Or am I missing some extra configuration?

using AutoFixture;

public class Program
{
    public static void Main()
    {
        var fixture = new Fixture();
        var students = fixture
            .Build<Student>()
            .With(st => st.School, new School
            {
                //SchoolId = Expecting AutoFixture would generate a unique SchoolId here
                Country = "England"
            })
            .CreateMany(2).ToList();

        foreach (var schoolId in students.Select(x => x.School.SchoolId))
        {
            Console.WriteLine($"schoolId: {schoolId ?? "null"}");
        }
    }
}

public class Student
{
    public string StudentId { get; set; }
    public string StudentName { get; set; }
    public School School { get; set; }
}

public class School
{
    public string SchoolId { get; set; }
    public string Country { get; set; }
}
2

There are 2 best solutions below

1
Ivan Gechev On

In your foreach you are selecting SchoolId, but you haven't specified what AutoFixture should use for it so it's just null. You can do the below:

var students = fixture
    .Build<Student>()
    .With(st => st.School, new School
    {
        SchoolId = Guid.NewGuid().ToString(),
        Country = "England"
    })
    .CreateMany(2).ToList();
5
Ozkan On

Here I have a possible solution, but I'm thinking there must be simpler way to do it.

var students = fixture
    .Build<Student>()
    .With(p => p.School, (IFixture f) => f.Build<School>().With(sc => sc.Country, "England").Create())
    .CreateMany(2).ToList();