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?
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.
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.
Use Assert. assertArrayEquals(Object[] expecteds, Object[] actuals) method to compare two array for content equality: Assert. assertArrayEquals(expected.
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 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.
You might want to check the documentation for List.equals
.
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