Map equality using Hamcrest

后端 未结 8 2012
鱼传尺愫
鱼传尺愫 2021-02-06 20:25

I\'d like to use hamcrest to assert that two maps are equal, i.e. they have the same set of keys pointing to the same values.

My current best guess is:

a         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 21:16

    Sometimes Map.equals() is enough. But sometimes you don't know the types of Maps is returned by code under tests, so you don't know if .equals() will properly compare that map of unknown type returned by code with map constructed by you. Or you don't want to bind your code with such tests.

    Additionally, constructing a map separately to compare the result with it is IMHO not very elegant:

    Map actual = methodUnderTest();
    
    Map expected = new HashMap();
    expected.put(new MyKey(1), new MyValue(10));
    expected.put(new MyKey(2), new MyValue(20));
    expected.put(new MyKey(3), new MyValue(30));
    assertThat(actual, equalTo(expected));
    

    I prefer using machers:

    import static org.hamcrest.Matchers.hasEntry;
    
    Map actual = methodUnderTest();
    assertThat(actual, allOf(
                          hasSize(3), // make sure there are no extra key/value pairs in map
                          hasEntry(new MyKey(1), new MyValue(10)),
                          hasEntry(new MyKey(2), new MyValue(20)),
                          hasEntry(new MyKey(3), new MyValue(30))
    ));
    

    I have to define hasSize() myself:

    public static  Matcher> hasSize(final int size) {
        return new TypeSafeMatcher>() {
            @Override
            public boolean matchesSafely(Map kvMap) {
                return kvMap.size() == size;
            }
    
            @Override
            public void describeTo(Description description) {
                description.appendText(" has ").appendValue(size).appendText(" key/value pairs");
            }
        };
    }
    

    And there is another variant of hasEntry() that takes matchers as parameters instead of exact values of key and value. This can be useful in case you need something other than equality testing of every key and value.

提交回复
热议问题