Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Created October 23, 2017 17:36
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 tomwhoiscontrary/16f5c8b55daff85ed3e02a57b32234df to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/16f5c8b55daff85ed3e02a57b32234df to your computer and use it in GitHub Desktop.
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
public class MoreMatchers {
public static <T, U> Matcher<T> hasFeature(String name, Function<T, U> getter, Matcher<U> subMatcher) {
return new FeatureMatcher<T, U>(subMatcher, name, name) {
@Override
protected U featureValueOf(T thing) {
return getter.apply(thing);
}
};
}
public static <K, V> Matcher<Map<K, V>> aMapWhoseEntries(Matcher<Iterable<? extends Map.Entry<K, V>>> subMatcher) {
return hasFeature("entries", Map::entrySet, subMatcher);
}
public static <K> Matcher<Map<K, ?>> aMapWhoseKeys(Matcher<Iterable<? extends K>> subMatcher) {
return hasFeature("entries", Map::keySet, subMatcher);
}
@SafeVarargs
public static <K, V> Matcher<SortedMap<K, V>> hasEntries(Map.Entry<K, Matcher<V>>... entries) {
return hasEntries(contains(Stream.of(entries)
.map(e -> isEntry(e.getKey(), e.getValue()))
.collect(Collectors.toList())));
}
public static <K, V> Matcher<SortedMap<K, V>> hasEntries(Matcher<? super Set<Map.Entry<K, V>>> subMatcher) {
return hasFeature("entries", Map::entrySet, subMatcher);
}
public static <K, V> Matcher<Map.Entry<K, V>> isEntry(K key, Matcher<V> valueMatcher) {
return Matchers.allOf(MoreMatchers.<K, V>hasKey(key),
MoreMatchers.<K, V>hasValue(valueMatcher));
}
public static <K, V> Matcher<Map.Entry<K, V>> hasKey(K key) {
return hasFeature("key", Map.Entry::getKey, equalTo(key));
}
public static <K, V> Matcher<Map.Entry<K, V>> hasValue(Matcher<V> subMatcher) {
return hasFeature("value", Map.Entry::getValue, subMatcher);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment