How to verify Map size using Hamcrest

Ramesh picture Ramesh · Mar 16, 2016 · Viewed 15.4k times · Source
Map<Integer, Map<String, String>> mapMap = new HashMap<Integer,Map<String, String>>();

Currently asserting like this

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

Are there any other methods like one used with Lists.

assertThat(someListReferenceVariable, hasSize(1));

Answer

eee picture eee · Mar 17, 2016

The good news

There is a matcher that does exactly what you want in the current master branch of the JavaHamcrest project. You can call it like so:

assertThat(mapMap, aMapWithSize(1));

And the bad news

Unfortunately this matcher is not in the latest release of Hamcrest (1.3).

[Update] And finally the very good news

The aforementioned matcher is included in the newly released version 2.1.