I'm writing some unit tests for a reporting system that uses some pretty complex composition of DTOs. To test the system I find myself writing a lot of code like this:
var items = new List<Item>
{
new Item
{
Things =
new List<Thing>
{
new Thing
{
Stuff =
new Stuff
{
Widgets = new List<Widget> {new Widget {Color = "Red"}}
},
Bobbles = new List<Bobble>{new Bobble(), new Bobble()}
}
}
}
};
This strikes me as verbose and cumbersome so my first thought was to use the builder pattern with a fluent interface:
var items = ItemBuilder.AddItem()
.WithThing()
.WithStuff()
.WithWidget()
.WithColor("Red");
Or something to that effect. Then it hit me that I have other objects I need to create like this and that it would be nice if I could use generics to apply this to any object I needed to:
var items = Builder.Add<Item>()
.With<Thing>()
.With<Stuff>()
.With<Widget>()
.With<Color>("Red");
Obviously these examples only approximate what the real interface might look like.
With such syntactic sugar as generics, lambdas and expression trees is this possible with C#?
I searched to see if anyone had attempted something like this but only found one or two incomplete series of blog posts on the topic. It seems to me that if it were possible there would be a complete example or an open source or commercial library available.
Sounds like NBuilder could satisfy your requirements: https://code.google.com/p/nbuilder/
It already exists, is widely used and very popular.