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

后端 未结 8 1269
一整个雨季
一整个雨季 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:42

    Here is how HashMap equal method works:

    public boolean equals(Object o) {
    ..........
    ..........
     Map m = (Map) o;
    ..........
        Iterator> i = entrySet().iterator();
        while (i.hasNext()) {
        Entry 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 !!

提交回复
热议问题