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

后端 未结 8 1262
一整个雨季
一整个雨季 2021-02-13 18:45

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

相关标签:
8条回答
  • 2021-02-13 19:35

    Too compare maps ,in your particular case :

    1)Check the size of the map if its equal

    Then use

        `assertTrue(expectedMap.equals(hashMap));` 
    

    In your Question bean you have to override the equals and hashcode method.

    0 讨论(0)
  • 2021-02-13 19:42

    Here is how HashMap equal method works:

    public boolean equals(Object o) {
    ..........
    ..........
     Map<K,V> m = (Map<K,V>) o;
    ..........
        Iterator<Entry<K,V>> i = entrySet().iterator();
        while (i.hasNext()) {
        Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
    ...........
    ...........
     return true;
    }
    

    Now since, it is invoking the equals method of Value objects, that means Value objects for a given key should be same (as governed by equals method).

    Above will help you to understand in what case your JUnit will pass. In your JUnit method you can use:

    public static void assertEquals(java.lang.Object expected,
                                    java.lang.Object actual)
    

    See link for more details.

    Cheers !!

    0 讨论(0)
提交回复
热议问题