Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assert that two HashMap with Javabean values are equal?

I have two HashMap<Integer, Question> maps that I would like to compare. Question in this case is a Javabean I have written.

How do I assert that both HashMap are equal? In this scenario, equal means that both HashMap contains exactly the same Question bean?

If it's at all relevant, I am writing a unit test using JUnit.

like image 470
Ayrx Avatar asked Sep 05 '13 03:09

Ayrx


People also ask

How do you check if all values in HashMap are equal?

We can compare two HashMap by comparing Entry with the equals() method of the Map returns true if the maps have the same key-value pairs that mean the same Entry.

How do you know if two maps are equal?

Map. equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.

How do you compare two Hashmaps by their keys?

If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap. keySet() function. It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set.

What does Equals method do in HashMap?

equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. HashMap uses equals() to compare the key to whether they are equal or not.


1 Answers

Using Guava you can do:

assertTrue(Maps.difference(expected, actual).areEqual());
like image 167
Ariel T Avatar answered Sep 23 '22 05:09

Ariel T