Skip to content

Instantly share code, notes, and snippets.

@kubek2k
Created May 25, 2015 08:21
Show Gist options
  • Save kubek2k/2c9bab54c8b08468ceea to your computer and use it in GitHub Desktop.
Save kubek2k/2c9bab54c8b08468ceea to your computer and use it in GitHub Desktop.
Handy hamcrest map matcher
public static class MapMatcher<K, V> extends TypeSafeMatcher<Map<K, V>> {
private final Map<K, V> desiredContents = new HashMap<>();
@Override
protected boolean matchesSafely(final Map<K, V> item) {
for(final Map.Entry<K, V> kvEntry : this.desiredContents.entrySet()) {
if (!kvEntry.getValue().equals(item.get(kvEntry.getKey()))) {
return false;
}
}
return true;
}
@Override
public void describeTo(final Description description) {
description.appendText("Contains entries: ").appendValue(this.desiredContents);
}
public MapMatcher<K, V> contains(final K key, final V value) {
this.desiredContents.put(key, value);
return this;
}
public static <K, V> MapMatcher<K, V> matcher() {
return new MapMatcher<K, V>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment