I am using nBuilder to populate an object graph, but it is only populating the value types. I want it to populate the reference types (related objects).
http://nbuilder.org/
NBuilder doesn't support automatically populating reference types at this time.
However, it is possible to do what you're wanting by using a builder to create each reference type.
At the moment you are probably doing this:
var person = Builder<Person>
.CreateNew()
.Build();
Assert.That(person.Name, Is.EqualTo("Name1"));
Assert.That(person.Address, Is.Null);
What you want to be doing is this:
var address = Builder<Address>
.CreateNew()
.Build();
var person2 = Builder<Person>
.CreateNew()
.With(x => x.Address = address)
.Build();
Assert.That(person2.Name, Is.EqualTo("Name1"));
Assert.That(person2.Address, Is.Not.Null);
Assert.That(person2.Address.Street, Is.EqualTo("Street1"));
Assert.That(person2.Address.Zipcode, Is.EqualTo("Zipcode1"));
A limitation I have found with NBuilder is that the data it generates for strings in this manner is that it is based off the property names e.g. Name1, Street1, Zipcode1 as you see above. I found myself using .Phrase() but it did not generate sensible random data and items like emails had to be pieced together.
You can download Faker.Net via nuget link here or use Visual Studio and have it create mock data as a part of your build command. Then you can use it to build your Person mock objects (using Faker/NBuilder again).
var addresses = Builder<Address>.CreateListOfSize(20)
.All()
.With(c => c.Street = Faker.StreetName().First())
.With(c => c.State = Faker.UsState().First())
.With(c => c.ZipCode = Faker.ZipCode().First())
.Build();
This blog post details some more examples.
This is not possible in NBuilder.
There is a hand-made tool though. This article contains code snippet that recursively calls NBuilder to create objects that fill reference and collection properties of the root object (down to given depth):
var recursiveObjectBuilder = new RecursiveObjectBuilder(graphDepth: 2, listSize: 3);
var complexObject = recursiveObjectBuilder.CreateGenericObject<ComplexType>(recursive:true);
Assert.NotNull(complexObject.ReferenceToOtherObject);
int someValue = complexObject.ReferenceToOtherObject.SomeValue;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With