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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
try
it works fine with Collections
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 andArrayList
is not an array—it's aList
.You can check the equality of two
ArrayLists
(really, any twoList
objects) usingequals
, so you should be able to use JUnit'sassertEquals
method and it will work just fine.You can override "equals" or "hashcode" method of Element type eg : ArralyList, ArrayList - (either primitive data type or custom data element), You can override the method, and compare all you data inside in that method and return true/ false accordingly.
You can then directly use assertEquals(arraylist1 , arraylist2) for your junit test.
Below is sample Object Class
}
Below is the sample class for Junit test :
}
What you probably want to use is
void org.junit.Assert.assertArrayEquals(Object[] expecteds, Object[] actuals)
. You just need to convert List to array withtoArray()
method, like that:Don't forget to import this assert.
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 implementjava.util.Comparable
interface with one methodint compareTo(T o)
.PS: The other possible solution is to use assertEquals and wrap your list into Set, like that:
Imagine
myArraylist
is an array list with contents"one", "two", "three"
This works fine:
Dont forget to import:
import static java.util.Arrays.asList;
If you are using some off the shelf junit framework like unitils etc they have methods like assertReflectionEquals (similary other framework does) where you can any two objects using reflection . If you are not using any third party junit framework , you can write your own similar generic method