Подтвердить что ты не робот

Как проверить размер карты с помощью 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));

4b9b3361

Ответ 1

Хорошие новости

Существует совпадение, которое делает именно то, что вы хотите в текущей главной ветки проекта JavaHamcrest. Вы можете назвать это так:

assertThat(mapMap, aMapWithSize(1));

И плохие новости

К сожалению, этот матчи не входит в последнюю версию Hamcrest (1.3).

Ответ 2

В 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)));