All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ext.test4j.hamcrest.collection.IsMapContaining Maven / Gradle / Ivy

There is a newer version: 2.5.0
Show newest version
package ext.test4j.hamcrest.collection;

import ext.test4j.hamcrest.Description;
import ext.test4j.hamcrest.Factory;
import ext.test4j.hamcrest.Matcher;
import ext.test4j.hamcrest.TypeSafeMatcher;

import java.util.Map;
import java.util.Map.Entry;

import static ext.test4j.hamcrest.core.IsAnything.anything;
import static ext.test4j.hamcrest.core.IsEqual.equalTo;

public class IsMapContaining extends TypeSafeMatcher> {
    private final Matcher keyMatcher;
    private final Matcher valueMatcher;

    public IsMapContaining(Matcher keyMatcher, Matcher valueMatcher) {
        this.keyMatcher = keyMatcher;
        this.valueMatcher = valueMatcher;
    }

    @Override
    public boolean matchesSafely(Map map) {
        for (Entry entry : map.entrySet()) {
            if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void describeMismatchSafely(Map map, Description mismatchDescription) {
      mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet());
    }

    public void describeTo(Description description) {
        description.appendText("map containing [")
                   .appendDescriptionOf(keyMatcher)
                   .appendText("->")
                   .appendDescriptionOf(valueMatcher)
                   .appendText("]");
    }

    @Factory
    public static  Matcher> hasEntry(Matcher keyMatcher, Matcher valueMatcher) {
        return new IsMapContaining(keyMatcher, valueMatcher);
    }

    @Factory
    public static  Matcher> hasEntry(K key, V value) {
        return new IsMapContaining(equalTo(key), equalTo(value));
    }
    
    @Factory
    public static  Matcher> hasKey(Matcher keyMatcher) {
        return new IsMapContaining(keyMatcher, anything());
    }

    @Factory
    public static  Matcher> hasKey(K key) {
        return new IsMapContaining(equalTo(key), anything());
    }

    @Factory
    public static  Matcher> hasValue(Matcher valueMatcher) {
        return new IsMapContaining(anything(), valueMatcher);
    }

    @Factory
    public static  Matcher> hasValue(V value) {
        return new IsMapContaining(anything(), equalTo(value));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy