无法断言该列表包含地图

时间:2015-11-16 14:14:45

标签: hamcrest

我想使用hamcrest来比较具有地图条目的列表。

    Map<String, String> aMapWithCertainEntries = new HashMap();
    aMapWithCertainEntries.put("entry1Key", "entry1Value");
    aMapWithCertainEntries.put("entry2Key", "entry2Value");

    List<Map<String,String>> listToTest = Arrays.asList(new Map[] {aMapWithCertainEntries});

    //I want to assert that list has a map with entry1Key, entry2Key keys and corresponding values
    assertThat(listToTest, hasItem(??))
    System.out.println();

在标记的地方?我想创建正确的匹配器来断言我的地图包含特定的键和值。

非常感谢任何帮助/指示。

1 个答案:

答案 0 :(得分:1)

如果您只想声明List包含整个内容符合预期的Map,最简单的方法是:

Map<String, String> expectedEntries = ....;
assertThat(listToTest, hasItem(expectedEntries));

但是,如果要确保列表包含包含给定子集条目的Map,则需要采用以下方法之一:

方法1:创建自定义匹配器

assertThat(listToTest, hasItem(new CustomTypeSafeMatcher<Map<String,String>>("an entrySet that contains " + expectedEntries.entrySet()) {
    @Override
    protected boolean matchesSafely(Map<String, String> o) {
        return hasItems(expectedEntries.entrySet().toArray()).matches(o.entrySet());
    }
}));

方法2:在每张地图上entrySet而非地图本身

assertThat(listToTest.stream().map(Map::entrySet).collect(Collectors.toList()),
    hasItem(hasItems(expectedEntries.entrySet().toArray(new Map.Entry[expectedEntries.size()]))));