views:

73

answers:

1

I've created a data builder in order to create test data in my unit tests. My data builders create defaults for all properties so that the tests that use them only need to specify the properties that are applicable to the test.

Consider the following builder:

public class CustomerBuilder
{
    public int id = 0;
    public Order order = new OrderBuilder().Build();

    public CustomerBuilder WithId(int id)
    {
        this.id = id;
        return this;
    }

    public CustomerBuilder WithOrder(Order order)
    {
        this.order = order;
        return this;
    }

    public Customer Build()
    {
        return new Customer(id, order);
    }
}

By doing this, if I need to create a customer in a test in which the id is important to me but the Order is irrelevant I can create the object as follows:

Customer c = new CustomerBuilder()
                  .WithId(99)
                  .Build();

Is this a good idea? Or is there any reason why it might not be best to assume how the non-primitive property ought to be constructed?

+2  A: 

This is a fine idea and is known as the Test Data Builder pattern :)

FWIW, I've created a general-purpose Test Data Builder called AutoFixture. This would enable you to simply write

var customer = new Fixture()
    .Build<Customer>()
    .With(c => c.Id, 99)
    .CreateAnonymous();

By using AutoFixture you don't need to write and maintain a lot of custom Test Data Builders, but otherwise it's a very worthwhile thing to do.

Mark Seemann