AutoFixture As Test Data Builder by Mark Seemann
In the original Gang of Four definition of a Design Pattern, several people must independently have arrived at the same general solution to a given problem before we can call a coding idiom a true Pattern. In this spirit, the Test Data Builder pattern is on the verge of becoming a true Design Pattern, since I came up with AutoFixture without having heard about Test Data Builder :)
The problem is the same: How do we create semantically correct test objects in a manner that is flexible and yet hides away irrelevant complexity?
Like others before me, I tried the Object Mother (anti?)pattern and found it lacking. To me the answer was AutoFixture, a library that heuristically builds object graphs using Reflection and built-in rules for specific types.
Although my original approach was different, you can certainly use AutoFixture as a generic Test Data Builder.
To demonstrate this, let's work with this (oversimplified) Order object model:
Assuming that we have an instance of the Fixture class (called fixture), we can create a new instance of the Order class with a ShippingAddress in Denmark:
var order = fixture.Build<Order>() .With(o => o.ShippingAddress, fixture.Build<Address>() .With(a => a.Country, "Denmark") .CreateAnonymous()) .CreateAnonymous();
While this works and follows the Test Data Builder pattern, I find this more concise and readable:
var order = fixture.CreateAnonymous<Order>(); order.ShippingAddress.Country = "Denmark";
The result is the same.
We can also add anonymous order lines to the order using this fluent interface:
var order = fixture.Build<Order>() .Do(o => fixture.AddManyTo(o.OrderLines)) .CreateAnonymous();
but again, I find it easier to simply let AutoFixture create a fully anonymous Order instance, and then afterwards modify the relevant parts:
var order = fixture.CreateAnonymous<Order>(); fixture.AddManyTo(order.OrderLines);
Whether you prefer one style over the other, AutoFixture supports them both.