Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to compare ArrayLists for equality using JUnit?

Tags:

What is an easy way to compare ArrayLists for equality using JUnit? Do I need to implement the equality interface? Or is there a simple JUnit method that makes it easier?

like image 569
Alex Baranosky Avatar asked Oct 03 '09 03:10

Alex Baranosky


People also ask

How do you check if two ArrayLists are equal 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.

How do you compare two ArrayLists 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.

How do you compare lists of objects in JUnit?

Use Assert. assertArrayEquals(Object[] expecteds, Object[] actuals) method to compare two array for content equality: Assert. assertArrayEquals(expected.

How do you assert two lists are equal?

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.


2 Answers

You need to do nothing special for list equality, just use assertEquals.

ArrayList and other lists implement equals() by checking that all objects in the corresponding positions of the lists are equal, using the equals() method of the objects. So you might want to check that the objects in the list implement equals correctly.

like image 182
starblue Avatar answered Oct 02 '22 03:10

starblue


You might want to check the documentation for List.equals.

like image 33
Tom Hawtin - tackline Avatar answered Oct 02 '22 04:10

Tom Hawtin - tackline