How to create child collections automatically using 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 as follows:

 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 is cumbersome with a large one. Is there a way for NBuilder to automatically fill all collections in an object?

By the way, I am not tied to NBuilder, so if there is another free library that will do this, I would gladly switch.

+4
source share
1 answer

Since you are not tied to NBuilder, you can add AutoFixture to work with collections .

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

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

This may seem like about the same amount of code, but it scales much better since you don’t need to add more code to populate more collections - it just happens by convention.

In AutoFixture 3.0, collection conventions will be present by default, which means you don't even need to add MultipleCustomization.

+7
source

Source: https://habr.com/ru/post/1393872/


All Articles