Test infrastructure, part 1 - building the builders

The basic brick of a test infrastructure is the ability to easily instantiate and set properties on the domain object under test. This can be achieved with a builder object, as per below. This builder exposes a fluent interface (in the chaining of methods withId and withName) to improve readibility.


Given a domain object such as

public class DomainObject{

   public DomainObject (Integer id, String name){
     this.id = id;
     this.name = name;
   }

   public Object doSomething(){
      ...
   }
}

then the associate builder will be:
public class DomainObjectBuilder{
   private Integer id="123";
   private String name="defaultName";

   public DomainObject build(){
      return new CustomObject(id,name);
   }

   public DomainObjectBuilder withId(Integer anId){
      this.id = anId;
      return this;
   }

   public DomainObjectBuilder withName(String name){
      this.name = name;
      return name;
   }
}
and a test for a DomainObject will look like:

DomainObject anObject = new DomainObjectBuilder()
.withId("345").withName("someTest").build();
assertThat (anObject.doSomething, is(anExpectedResult));

An alternative approach would be to do without a builder and simply add setters on the domain object, setters which would be invoked during the tests. The major drawback of this technique is that adding setters breaks immutability.

No comments:

Post a Comment