~ubuntu-branches/ubuntu/raring/libhamcrest1.2-java/raring

« back to all changes in this revision

Viewing changes to hamcrest-library/src/main/java/org/hamcrest/collection/IsMapContaining.java

  • Committer: Package Import Robot
  • Author(s): Brian Thomason
  • Date: 2011-12-02 17:55:55 UTC
  • Revision ID: package-import@ubuntu.com-20111202175555-xuj86jbpi8mehr1o
Tags: upstream-1.2
ImportĀ upstreamĀ versionĀ 1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package org.hamcrest.collection;
 
2
 
 
3
import org.hamcrest.Description;
 
4
import org.hamcrest.Factory;
 
5
import org.hamcrest.Matcher;
 
6
import org.hamcrest.TypeSafeMatcher;
 
7
 
 
8
import static org.hamcrest.core.IsEqual.equalTo;
 
9
 
 
10
import java.util.Map;
 
11
import java.util.Map.Entry;
 
12
 
 
13
public class IsMapContaining<K,V> extends TypeSafeMatcher<Map<? extends K, ? extends V>> {
 
14
    private final Matcher<? super K> keyMatcher;
 
15
    private final Matcher<? super V> valueMatcher;
 
16
 
 
17
    public IsMapContaining(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher) {
 
18
        this.keyMatcher = keyMatcher;
 
19
        this.valueMatcher = valueMatcher;
 
20
    }
 
21
 
 
22
    @Override
 
23
    public boolean matchesSafely(Map<? extends K, ? extends V> map) {
 
24
        for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
 
25
            if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) {
 
26
                return true;
 
27
            }
 
28
        }
 
29
        return false;
 
30
    }
 
31
 
 
32
    @Override
 
33
    public void describeMismatchSafely(Map<? extends K, ? extends V> map, Description mismatchDescription) {
 
34
      mismatchDescription.appendText("map was ").appendValueList("[", ", ", "]", map.entrySet());
 
35
    }
 
36
 
 
37
    public void describeTo(Description description) {
 
38
        description.appendText("map containing [")
 
39
                   .appendDescriptionOf(keyMatcher)
 
40
                   .appendText("->")
 
41
                   .appendDescriptionOf(valueMatcher)
 
42
                   .appendText("]");
 
43
    }
 
44
 
 
45
    @Factory
 
46
    public static <K,V> Matcher<Map<? extends K,? extends V>> hasEntry(Matcher<? super K> keyMatcher, Matcher<? super V> valueMatcher) {
 
47
        return new IsMapContaining<K,V>(keyMatcher, valueMatcher);
 
48
    }
 
49
 
 
50
    @Factory
 
51
    public static <K,V> Matcher<Map<? extends K,? extends V>> hasEntry(K key, V value) {
 
52
        return IsMapContaining.<K,V>hasEntry(equalTo(key), equalTo(value));
 
53
    }
 
54
}