无法断言该列表包含地图
Unable to assert that list contains a map
我想使用 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();
在标有??的地方我想创建正确的匹配器来断言我的地图包含特定的键和值。
任何 help/pointers 将不胜感激。
如果您只想断言 List 包含一个 Map,其 entire 内容符合预期,最简单的方法是:
Map<String, String> expectedEntries = ....;
assertThat(listToTest, hasItem(expectedEntries));
但是,如果您想确保列表包含一个包含给定 子集 条目的映射,您将需要采取以下方法之一:
方法 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()]))));
我想使用 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();
在标有??的地方我想创建正确的匹配器来断言我的地图包含特定的键和值。
任何 help/pointers 将不胜感激。
如果您只想断言 List 包含一个 Map,其 entire 内容符合预期,最简单的方法是:
Map<String, String> expectedEntries = ....;
assertThat(listToTest, hasItem(expectedEntries));
但是,如果您想确保列表包含一个包含给定 子集 条目的映射,您将需要采取以下方法之一:
方法 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()]))));