如何使用Hamcrest验证地图大小

Ram*_*esh 24 java junit hamcrest

Map<Integer, Map<String, String>> mapMap = new HashMap<Integer,Map<String, String>>();
Run Code Online (Sandbox Code Playgroud)

目前断言这样

assertThat(mapMap.size(), is(equalTo(1)));
Or
assertThat(mapMap.values(), hasSize(1));
Run Code Online (Sandbox Code Playgroud)

是否有任何其他方法,如与列表一起使用的方法.

assertThat(someListReferenceVariable,hasSize(1));

eee*_*eee 16

好消息

有一个匹配器在JavaHamcrest项目的当前主分支中完全按照您的要求执行.你可以像这样调用它:

assertThat(mapMap, aMapWithSize(1));
Run Code Online (Sandbox Code Playgroud)

而坏消息

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

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

上述匹配包括在新发布的2.1版本.

  • 它包括一个空地图的匹配器!`anEmptyMap()`,感谢您的链接。 (3认同)

Rub*_*ben 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

测试:

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