Reputation: 3246
I thought it was going to be easy but can anyone tell me how I can test HashMap to see if it has some value in JUnit?
assertThat(myMap, ??);
I tried something like:
assertThat(myMap, hasEntry("Key", notNullValue()));
...But I couldn't make it compile since my import to hasEntry and notNullValue() is correct. Does anyone know what the correct import pkg for them should be?
Upvotes: 5
Views: 21521
Reputation: 5756
I don't like the assertTrue
approaches, because the feedback is quite limited when the assertion fails.
It can be done with assertThat
like this:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
assertThat(myMap, hasEntry(is("Key"), notNullValue()));
Upvotes: 0
Reputation: 59146
To check the key is in the map:
import static org.junit.Assert.assertTrue;
...
assertTrue(myMap.containsKey("Key"));
Alternatively, to check it has a non-null value:
import static org.junit.Assert.assertNotNull;
...
assertNotNull(myMap.get("Key"));
Upvotes: 0
Reputation: 31087
You're after hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher)
.
The underlying implementation is in IsMapContaining
but,
like most matchers in Hamcrest, it can also be found through org.hamcrest.Matchers
, in hamcrest-library
.
Otherwise, your syntax is correct, and Matchers
also defines notNullValue()
.
Upvotes: 3
Reputation: 687
import static org.junit.Assert.AssertTrue;
assertTrue(myMap.containsKey("yourKey") && myMap.get("yourKey") != null)
Upvotes: 3