【问题标题】:How to create child collections automatically with NBuilder?如何使用 NBuilder 自动创建子集合?
【发布时间】:2012-01-30 23:58:13
【问题描述】:

给定以下类:

class Department
{
    public String Name { get; set; }
    public IList<Employee> Employees { get; set; }
}
class Employee
{
    public String Name { get; set; }
    public String Address { get; set; }
}

使用 NBuilder,我可以通过以下方式创建部门对象并分配 10 名员工:

var employees = Builder<Employee>.CreateListOfSize(10).Build();
var department = Builder<Department>
    .CreateNew()
    .With(d=>d.Employees = employees)
    .Build();

这适用于少量集合,但对于大量集合来说会很麻烦。有没有办法让 NBuilder 自动填充对象中的所有集合?

顺便说一句,我不依赖于 NBuilder,所以如果有另一个免费的库可以做到这一点,我会非常乐意切换。

【问题讨论】:

    标签: .net nbuilder


    【解决方案1】:

    由于您未绑定到 NBuilder,因此您可以使用 AutoFixture 添加 conventions for working with collections

    例如,要创建一个有 10 名员工的部门实例,您可以这样做:

    var fixture = new Fixture().Customize(new MultipleCustomization());
    fixture.RepeatCount = 10;
    
    var dep = fixture.CreateAnonymous<Department>();
    

    这可能看起来与代码量大致相同,但它的扩展性要好得多,因为您不需要添加更多代码来填充更多集合 - 这只是按照惯例发生的。

    在 AutoFixture 3.0 中,默认情况下会存在集合的约定,这意味着您甚至不需要添加 MultipleCustomization。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2014-10-13
      • 2018-08-06
      • 2016-05-14
      • 1970-01-01
      相关资源
      最近更新 更多