Tricks with Test Data Builders: Combining Builders

Three Builders

If an object built with a Test Data Builder contains other objects built with other Test Data Builders, you can pass one builder to another to save keystrokes and reduce noise, making tests easier to read. For example, instead of:

Invoice invoice = new InvoiceBuilder()
    .withRecipient(new RecipientBuilder()
        .withAddress(new AddressBuilder()
            .withNoPostcode()
            .build())
        .build())
    .build();

You can write:

Invoice invoice = new InvoiceBuilder()
    .withRecipient(new RecipientBuilder()
        .withAddress(new AddressBuilder()
            .withNoPostcode())))
    .build();

The result is significantly easier to read.

Copyright © 2007 Nat Pryce. Posted 2007-12-13. Share it.