Map equality using Hamcrest

后端 未结 8 2175
鱼传尺愫
鱼传尺愫 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:00

    The shortest way I've come up with is two statements:

    assertThat( affA.entrySet(), everyItem(isIn(affB.entrySet())));
    assertThat( affB.entrySet(), everyItem(isIn(affA.entrySet())));
    

    But you can probably also do:

    assertThat(affA.entrySet(), equalTo(affB.entrySet()));
    

    depending on the implementations of the maps, and sacrificing the clarity of the difference report: that would just tell you that there is a difference, while the statement above would also tell you which one.

    UPDATE: actually there is one statement that works independently of the collection types:

    assertThat(affA.entrySet(), both(everyItem(isIn(affB.entrySet()))).and(containsInAnyOrder(affB.entrySet())));
    

提交回复
热议问题