使用With子句传入部分填充对象时CreateMany生成Null值问题
AutoFixture生成Student时SchoolId为null的问题解决
问题场景
你用AutoFixture的CreateMany(2)生成2个Student对象,要求两个对象的School.Country固定为"England",且School.SchoolId是唯一值,但实际生成的students里School.SchoolId全是null,不符合预期。你的代码如下:
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; } }
错误原因
你直接手动new School()创建实例并传给.With()方法,AutoFixture只会处理它自己生成的对象,不会给你手动实例化的对象自动填充属性,所以SchoolId一直是null。而且这里的.With()是直接替换掉AutoFixture原本要生成的School实例,完全跳过了它的自动填充逻辑。
解决方法
有两种常用的正确写法,都能让AutoFixture自动生成唯一的SchoolId,同时保证Country为"England":
方法1:直接嵌套配置School的Country属性
让AutoFixture自动生成完整的School对象,只指定需要固定的Country属性:
var students = fixture .Build<Student>() .With(st => st.School.Country, "England") .CreateMany(2).ToList();
方法2:让AutoFixture生成School后再修改属性
如果需要更灵活的配置,可以先让AutoFixture生成School对象,再修改Country属性,这样SchoolId会被自动填充:
var students = fixture .Build<Student>() .With(st => st.School, fixture.Build<School>() .With(s => s.Country, "England") .Create()) .CreateMany(2).ToList();
或者更简洁的写法:
var students = fixture .Build<Student>() .With(st => st.School, fixture.Create<School>(s => s.Country = "England")) .CreateMany(2).ToList();
效果验证
运行修改后的代码,每个Student的School都会有唯一的SchoolId,同时Country固定为"England",输出的schoolId不再是null。
内容的提问来源于stack exchange,提问作者Ozkan
相关产品推荐
相关产品推荐

