io.github.olib963.javatest.matchers.internal.EntryMatcher Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of javatest-matchers Show documentation
Show all versions of javatest-matchers Show documentation
Matchers to create assertions from common conditions
package io.github.olib963.javatest.matchers.internal;
import io.github.olib963.javatest.matchers.MatchResult;
import io.github.olib963.javatest.matchers.Matcher;
import java.util.Map;
import java.util.Optional;
public class EntryMatcher implements Matcher> {
private final Matcher keyMatcher;
private final Matcher valueMatcher;
public EntryMatcher(Matcher keyMatcher, Matcher valueMatcher) {
this.keyMatcher = keyMatcher;
this.valueMatcher = valueMatcher;
}
@Override
public MatchResult matches(Map.Entry entry) {
var key = entry.getKey();
var keyResult = keyMatcher.matches(key);
var keyMismatch = keyResult.mismatch.map(m -> "Key " + key + " " + m);
var value = entry.getValue();
var valueResult = valueMatcher.matches(value);
var valueMismatch = valueResult.mismatch.map(m -> "value " + key + " " + m);
boolean matches = keyResult.matches && valueResult.matches;
return MatchResult.of(matches, combine(keyMismatch, valueMismatch));
}
@Override
public String describeExpected() {
return "have key that was expected to " + keyMatcher.describeExpected()
+ " and value that was expected to " + valueMatcher.describeExpected();
}
private Optional combine(Optional a, Optional b) {
if (a.isPresent()) {
var aStr = a.get();
String withB = b.map(bStr -> aStr + " " + bStr).orElse(aStr);
return Optional.of(withB);
}
return b;
}
}