Search code examples
javahashmapcomparison

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.


Solution

  • 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>