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. Is there a way to test for the equality of two arrayLists of whatever type in Junit?
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.
A simple solution to compare two lists of primitive types for equality is using the List. equals() method. It returns true if both lists have the same size, and all corresponding pairs of elements in both lists are equal.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With