Wednesday, April 22, 2009

Unit Testing Recipes

A lot of times i tend to come across unit tests where the developer has to create a List and compare the equality of a returned List with some expected List. As an example consider the following test Case

public void testResultsHasSameElements(){
List()expectedResults=new ArrayList();
expectedResults.add("James");
expectedResults.add("Jack");
List customerNames=CustomerDTO.getCustomerNames();
for(String name:customerNames){
assertEquals(name,expectedResult.get(0));
assertEquals(name,expectedResult.get(1));
}

}

If we look at the above testcase, it involves a lot of typing. We can simplify the above test using the fact that 2 Lists are equal if they contain the same objects at the same index. Another optimization which can be used is the Arrays.toList method to create the expectedResults list
The improved version of the test would look like

public void testResultsHasSameElements(){
List()expectedResults=Arrays.asList(
new String[]{"James","Jack"}
);

customerNames=CustomerDTO.getCustomerNames();
assertEquals(customerNames,expectedResult);
}

}

The emperor and me beaching

The Devil next door

Kaiser The Emperor