ArrayList equality JUnit testing

What you probably want to use is void org.junit.Assert.assertArrayEquals(Object[] expecteds, Object[] actuals). You just need to convert List to array with toArray() method, like that:

ArrayList<Token> list1 = buildListOne(); // retrieve or build list
ArrayList<Token> list2 = buildListTwo(); // retrieve or build other list with same items

assertArrayEquals(list1.toArray(), list2.toArray());

Don't forget to import this assert.

import static org.junit.Assert.assertArrayEquals;

But this methods only works if items in both lists have same order. If the order is not guaranteed, then you need to sort the lists with Collections.sort() method, but your object need to implement java.util.Comparable interface with one method int compareTo(T o).

PS: The other possible solution is to use assertEquals and wrap your list into Set, like that:

assertEquals(new HashSet<Token>(list1), new HashSet<Token>(list2));

I want to use the assertArrayEquals(ArrayList<Token>, ArrayList<Token>) with these arguments (i.e. arrayList of tokens). But Java tells me I need to create such a method.

It's telling you that you need to create the method because there is no such method in the JUnit library. There isn't such a method in the JUnit library because assertArrayEquals is for comparing arrays, and and ArrayList is not an array—it's a List.

Is there a way to test for the equality of two arrayLists of whatever type in Junit?

You can check the equality of two ArrayLists (really, any two List objects) using equals, so you should be able to use JUnit's assertEquals method and it will work just fine.

Tags:

Java

Junit