Skip to content

Instantly share code, notes, and snippets.

@splatch
Created June 30, 2015 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save splatch/164792e1152b2f24abc9 to your computer and use it in GitHub Desktop.
Save splatch/164792e1152b2f24abc9 to your computer and use it in GitHub Desktop.
Simple hamcrest map matcher which ensures that argument contains given keys and values.
import org.hamcrest.Description;
import org.mockito.ArgumentMatcher;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapMatcher extends ArgumentMatcher<Map> {
private final Map<Object, Object> map = new HashMap<Object, Object>();
public MapMatcher(Object ... wantedKeyValuePair) {
if (wantedKeyValuePair.length > 0 && wantedKeyValuePair.length % 2 != 0) {
throw new IllegalArgumentException("Invalid number of parameters. Missing value for key " + wantedKeyValuePair[wantedKeyValuePair.length - 1]);
}
for (int i = 0; i < wantedKeyValuePair.length; i = i + 2) {
map.put(wantedKeyValuePair[i], wantedKeyValuePair[i + 1]);
}
}
public MapMatcher(Map wanted) {
map.putAll(wanted);
}
public void describeTo(Description description) {
description.appendText("map(");
for (Entry entry : map.entrySet()) {
description.appendText("{");
description.appendValue(entry.getKey());
description.appendText(",");
description.appendValue(entry.getValue());
description.appendText("}");
}
description.appendText(")");
}
@Override
public boolean matches(Object argument) {
if (argument instanceof Map) {
return matches((Map) argument);
}
return false;
}
private boolean matches(Map argument) {
for (Object key : map.keySet()) {
if (!argument.containsKey(key)) {
return false;
}
if (!map.get(key).equals(argument.get(key))) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment