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,


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

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

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);
    }
}
Test Data Builder with Fluent lambda interface

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s