Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sometimes <code>Map.equals()</code> is enough. But sometimes you don't know the types of <code>Map</code>s is returned by code under tests, so you don't know if <code>.equals()</code> will properly compare that map of unknown type returned by code with map constructed by you. Or you don't want to bind your code with such tests.</p> <p>Additionally, constructing a map separately to compare the result with it is IMHO not very elegant:</p> <pre><code>Map&lt;MyKey, MyValue&gt; actual = methodUnderTest(); Map&lt;MyKey, MyValue&gt; expected = new HashMap&lt;MyKey, MyValue&gt;(); 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)); </code></pre> <p>I prefer using machers:</p> <pre><code>import static org.hamcrest.Matchers.hasEntry; Map&lt;MyKey, MyValue&gt; 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)) )); </code></pre> <p>I have to define <code>hasSize()</code> myself:</p> <pre><code>public static &lt;K, V&gt; Matcher&lt;Map&lt;K, V&gt;&gt; hasSize(final int size) { return new TypeSafeMatcher&lt;Map&lt;K, V&gt;&gt;() { @Override public boolean matchesSafely(Map&lt;K, V&gt; kvMap) { return kvMap.size() == size; } @Override public void describeTo(Description description) { description.appendText(" has ").appendValue(size).appendText(" key/value pairs"); } }; } </code></pre> <p>And there is another variant of <code>hasEntry()</code> that takes matchers as parameters instead of exact values of key and value. This can be useful in case you need something other than equality testing of every key and value.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload