我想使用hamcrest断言两个映射是相等的,即它们具有指向相同值的同一组键。
我目前最好的猜测是:
assertThat( affA.entrySet(), hasItems( affB.entrySet() );这意味着:
类型为
assertThat(T, Matcher<T>)的方法Assert不适用于参数(Set<Map.Entry<Householdtypes,Double>>, Matcher<Iterable<Set<Map.Entry<Householdtypes,Double>>>>)
我还研究了containsAll的变体,以及hamcrest包提供的其他一些变体。谁能给我指明正确的方向?还是我必须写一个定制的匹配器?
发布于 2012-08-27 15:45:10
我想出的最短的方法是两种说法:
assertThat( affA.entrySet(), everyItem(isIn(affB.entrySet())));
assertThat( affB.entrySet(), everyItem(isIn(affA.entrySet())));但你也可以这样做:
assertThat(affA.entrySet(), equalTo(affB.entrySet()));取决于映射的实现,并牺牲差异报告的清晰度:这只会告诉您存在差异,而上面的语句也会告诉您是哪一个。
UPDATE:实际上有一条语句独立于集合类型工作:
assertThat(affA.entrySet(), both(everyItem(isIn(affB.entrySet()))).and(containsInAnyOrder(affB.entrySet())));发布于 2011-11-19 19:50:07
有时候Map.equals()就足够了。但是有时您不知道Map的类型是由测试中的代码返回的,所以您不知道.equals()是否会正确地将代码返回的未知类型的映射与您构造的映射进行比较。或者您不希望将代码绑定到这样的测试中。
此外,分别构造一个地图来比较结果是IMHO不太优雅:
Map<MyKey, MyValue> actual = methodUnderTest();
Map<MyKey, MyValue> expected = new HashMap<MyKey, MyValue>();
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));我更喜欢用机器:
import static org.hamcrest.Matchers.hasEntry;
Map<MyKey, MyValue> 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))
));我必须自己定义hasSize():
public static <K, V> Matcher<Map<K, V>> hasSize(final int size) {
return new TypeSafeMatcher<Map<K, V>>() {
@Override
public boolean matchesSafely(Map<K, V> kvMap) {
return kvMap.size() == size;
}
@Override
public void describeTo(Description description) {
description.appendText(" has ").appendValue(size).appendText(" key/value pairs");
}
};
}还有另一个hasEntry()变体,它以匹配器作为参数,而不是键和值的确切值。如果您需要对每个键和值进行平等测试以外的其他东西,这可能很有用。
发布于 2015-04-16 16:10:26
我喜欢使用番石榴ImmutableMap。它们支持Map.equals(),并且易于构建。唯一的诀窍是显式指定类型参数,因为hamcrest将采用ImmutableMap类型。
assertThat( actualValue,
Matchers.<Map<String, String>>equalTo( ImmutableMap.of(
"key1", "value",
"key2", "other-value"
) ) );https://stackoverflow.com/questions/2509293
复制相似问题