Test Data Builder Pattern

The test data builder pattern is a pattern as the name implies, is to build test data. It works on the principle of setting the details in teh constructor and then have a method that builds (returns) the built object. Default values are set in the constructor and the methods are then used to override those defaults.

package com.beanietech;

public class AddressBuilder {

private String firstName;
private String lastName;
private String Address;

public AddressBuilder() {
this.withAddress("5 Fake St");

public AddressBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;

public AddressBuilder withLastName(String lastName) {
this.lastName = lastName;
return this;

public AddressBuilder withAddress(String address) {
this.Address = address;
return this;

public String build() {
String message = this.firstName + "," + this.lastName + "," + this.Address;
return message;

public static void main(String... args) {
AddressBuilder A = new AddressBuilder()


As you can see, the code is a little different to your usual getter and setter code. By using the with methods. The with method return the current object, so it allows you to chain with statements together.

For example:

 Address A = new Address()

Also, by indenting the statement over multiple lines, it makes it more readable. It also gives the advantage that you can comment out certain with lines to debug or change the data without affecting the execution.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.