Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create child collections automatically with NBuilder?

Tags:

.net

nbuilder

Given the following classes:

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

With NBuilder I can create a department object and assign 10 employees the following way:

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

This works with a small number of collections but it gets cumbersome with a large one. Is there a way to have NBuilder populate all collections in the object automatically?

By the way, I'm not tied to NBuilder so if there's another free library that does this I'd be more than happy to switch.

like image 366
Manuel Avatar asked Feb 21 '23 16:02

Manuel


1 Answers

Since you're not tied to NBuilder, with AutoFixture you can add conventions for working with collections.

As an example, to create a Department instance with 10 employees, you can do this:

var fixture = new Fixture().Customize(new MultipleCustomization());
fixture.RepeatCount = 10;

var dep = fixture.CreateAnonymous<Department>();

That may look like approximately the same amount of code, but it scales much better since you don't need to add more code to populate more collections - that just happens by convention.

In AutoFixture 3.0, the conventions for collections will be there by default, which means that you don't even need to add the MultipleCustomization.

like image 162
Mark Seemann Avatar answered Jun 13 '23 04:06

Mark Seemann