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

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

    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.

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

    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>
    
    0 讨论(0)
  • 2021-02-13 19:28

    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.

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

    Using Guava you can do:

    assertTrue(Maps.difference(expected, actual).areEqual());
    
    0 讨论(0)
  • 2021-02-13 19:32

    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

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

    I found the keySet method of the map class useful

            assertEquals(map1.keySet(), map2.keySet());
    
    0 讨论(0)
提交回复
热议问题