I have two HashMap
maps that I would like to compare. Question
in this case is a Javabean I have written.
How do I ass
You can use compare(-,-)
(Mostly used for sorting
purpose) of Comparator
interface to implement custom comparison between objects as your requirement. Or use equals()
method to compare objects.
Here is the solution I eventually ended up using which worked perfectly for unit testing purposes.
for(Map.Entry<Integer, Question> entry : questionMap.entrySet()) {
assertReflectionEquals(entry.getValue(), expectedQuestionMap.get(entry.getKey()), ReflectionComparatorMode.LENIENT_ORDER);
}
This involves invoking assertReflectionEquals()
from the unitils
package.
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-core</artifactId>
<version>3.3</version>
<scope>test</scope>
</dependency>
If your Question class implements equals
then you can just do
assertEquals(expectedMap, hashMap);
assertTrue(expectedMap.equals(hashMap));
The Map interface specifies that two Maps are equal if they contain equal elements for equal keys.
Using Guava you can do:
assertTrue(Maps.difference(expected, actual).areEqual());
if your bean class has a field which will be unique for every object you create then you should override equals and hashcode method in ur bean class with that field
I found the keySet method of the map class useful
assertEquals(map1.keySet(), map2.keySet());