CreateMany 在 With 子句中使用部分填充的对象时会生成空值

问题描述 投票:0回答:1

有了下面的代码,我使用

CreateMany(2)
生成 2 个学生对象,这两个对象的
SchoolName
必须是
"Oxford"
。另一个
SchoolId
必须是唯一的。

但是下面的

students
变量包含
School
对象,其中
null
作为 SchoolId,而我期望那里有唯一的值。我究竟做错了什么?或者我缺少一些额外的配置?

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
                SchoolName = "Oxford"
            })
            .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 SchoolName { get; set; }
}
c# autofixture
1个回答
0
投票

在您的

foreach
中,您选择了
SchoolId
,但您尚未指定
AutoFixture
应使用什么,因此它只是
null
。 您可以执行以下操作:

var students = fixture
    .Build<Student>()
    .With(st => st.School, new School
    {
        SchoolId = Guid.NewGuid().ToString(),
        SchoolName = "Oxford"
    })
    .CreateMany(2).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.