Test Data Builder with Fluent lambda interface


With the builder pattern, you can create an object in a more flexible and explicit way. And C# lamdba syntax makes the fluent interface more succinct

For example,

[sourcecode language="csharp"]

User fred = new UserTestDataBuilder()
.With(u => u.Name = "fred")
.With(u => u.Reputation = 900)
.With(u => u.ScholarBadge = true)
.With(u => u.CriticBadge = true)

[/sourcecode]

You just need an Action<T> method and a class for the properties to populate.

[sourcecode language="csharp"]
public class UserSpec
{
public string Name {get; set;}
public int Reputation {get; set;}
...
}

public class UserTestDataBuilder()
{
private UserSpec _userSpec = new UserSpec();
public UserTestDataBuilder With(Action&lt;UserSpec&gt; action)
{
action(_userSpec);
return this;
}

public User Build()
{
return new User(_userSpec.Name, _userSpec.Reputation,
_userSpec.ScholarBadge, _userSpec.CriticBadge);
}
}
[/sourcecode]