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();

List customerNames=CustomerDTO.getCustomerNames();
for(String name:customerNames){


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(){

new String[]{“James”,”Jack”}



One Response to Unit Testing Recipes

  1. Ashish says:

    Hey Maneesh, Long time!

    using Arrays.asList is certainly neat and convenient way to create lists, that contain a few items that you have as individual objects, and so it is, however, there is a DANGER…

    Arrays.asList in intended to be used to represent an array as a list, but it is just a simple List like wrapper around the original array. This means that just as the size of the array can not be changed, the size of the list can not be changed. The list that is produced by Arrays.asList will throw an UnsupportedOperationException it you try add or remove elements.

    Mostly this is fine in tests etc. If your test passes with one of these lists, it should pass with any list. It is probably best NOT to use this approach in production code as you don’t know what any downstream users of this list will need to do with it. If the list really IS a list representation of an array, that’s different, although you might ask yourself why you are using an array in the first place…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: