如何使用Hamcrest验证地图大小

时间:2016-03-16 08:48:56

标签: java junit hamcrest

Map<Integer, Map<String, String>> mapMap = new HashMap<Integer,Map<String, String>>();

目前断言如此

assertThat(mapMap.size(), is(equalTo(1)));
Or
assertThat(mapMap.values(), hasSize(1));

是否有其他方法,例如与列表一起使用的方法。

  

assertThat(someListReferenceVariable,hasSize(1));

3 个答案:

答案 0 :(得分:15)

好消息

有一个匹配器可以在当前master branch of the JavaHamcrest project中完全按照您的要求执行操作。 你可以这样称呼它:

assertThat(mapMap, aMapWithSize(1));

坏消息

不幸的是,这个匹配器不在Hamcrest(1.3)的最新版本中。

[更新]最后是非常好消息

新发布的2.1版中的aforementioned matcher is included

答案 1 :(得分:5)

Hamcrest 1.3中没有,但您可以轻松创建自己的:

public class IsMapWithSize<K, V> extends FeatureMatcher<Map<? extends K, ? extends V>, Integer> {
    public IsMapWithSize(Matcher<? super Integer> sizeMatcher) {
        super(sizeMatcher, "a map with size", "map size");
    }

    @Override
    protected Integer featureValueOf(Map<? extends K, ? extends V> actual) {
        return actual.size();
    }

    /**
     * Creates a matcher for {@link java.util.Map}s that matches when the
     * <code>size()</code> method returns a value that satisfies the specified
     * matcher.
     * <p/>
     * For example:
     * 
     * <pre>
     * Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
     * map.put(&quot;key&quot;, 1);
     * assertThat(map, isMapWithSize(equalTo(1)));
     * </pre>
     * 
     * @param sizeMatcher
     *            a matcher for the size of an examined {@link java.util.Map}
     */
    @Factory
    public static <K, V> Matcher<Map<? extends K, ? extends V>> isMapWithSize(Matcher<? super Integer> sizeMatcher) {
        return new IsMapWithSize<K, V>(sizeMatcher);
    }

    /**
     * Creates a matcher for {@link java.util.Map}s that matches when the
     * <code>size()</code> method returns a value equal to the specified
     * <code>size</code>.
     * <p/>
     * For example:
     * 
     * <pre>
     * Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
     * map.put(&quot;key&quot;, 1);
     * assertThat(map, isMapWithSize(1));
     * </pre>
     * 
     * @param size
     *            the expected size of an examined {@link java.util.Map}
     */
    @Factory
    public static <K, V> Matcher<Map<? extends K, ? extends V>> isMapWithSize(int size) {
        Matcher<? super Integer> matcher = equalTo(size);
        return IsMapWithSize.<K, V> isMapWithSize(matcher);
    }

}

测试:

    Map<String, Integer> map = new HashMap<>();
    map.put("key", 1);
    assertThat(map, isMapWithSize(1));
    assertThat(map, isMapWithSize(equalTo(1)));

答案 2 :(得分:0)

您可以使用“不”和“任何”来检查

import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.not;

not(hasEntry(any(Object.class), any(Object.class)))