Test infrastructure, part 2 - randomizing data

The builder created in part 1 initialises the domain object under test with predefined values:

 id {123} and name {defaultName}

public class DomainObjectBuilder{
   private Integer id="123";
   private String name="defaultName";

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

The objects thus constructed by the builder are then used in tests. So far so good. Sometimes though we want these tests to work a little harder, and prove that they can run ok with different input values. The methods below can be used to that end, building on the RandomStringUtils and RandomUtils methods from Apache Commons.

eg. to randomise a string by adding a 2 digits to the end of it.
public String randomizedString(String aString){
   return aString+RandomStringUtils.randomAlphaNumeric(2);
}
and the builder becomes (assuming the randomizedString method is statically imported)
public class DomainObjectBuilder{
   private Integer id=randomizedString("123");
   private String name=randomizedString("defaultName");

   public DomainObject build(){
      return new CustomObject(id,name);
   }
   ....
}
Each invocation of the DomainOBjectBuilder.build() method will now return domain objects with slightly different values. Of course it's not only strings which can be randomized. The same principles applies to enums:
public static <T extends Enum> T randomizedEnum (class <T> enumClass){
   T[] enumConstants = enumClass.getEnumConstants();
  return enumConstants[RandomUtils.nextInt(enumConstants.length);
}
... and to lists.
public static <T>  T randomElementFromList(List aList){
   return aList.get(RandomUtils.nextInt(aList.size()));   
}

No comments:

Post a Comment