1 /*
2 BSD License
3
4 Copyright (c) 2000-2006, www.hamcrest.org
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10 Redistributions of source code must retain the above copyright notice, this list of
11 conditions and the following disclaimer. Redistributions in binary form must reproduce
12 the above copyright notice, this list of conditions and the following disclaimer in
13 the documentation and/or other materials provided with the distribution.
14
15 Neither the name of Hamcrest nor the names of its contributors may be used to endorse
16 or promote products derived from this software without specific prior written
17 permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
22 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
25 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
27 WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28 DAMAGE.
29 */
30 package dev.aherscu.qa.testing.utils.assertions.impl.matcher;
31
32 import static org.hamcrest.core.IsEqual.equalTo;
33
34 import java.util.Map;
35
36 import org.hamcrest.Description;
37 import org.hamcrest.Matcher;
38
39 public class IsMapContainingKey<K> extends MapTypeSafeMatcher<Map<K, ?>> {
40 private final Matcher<K> keyMatcher;
41
42 public IsMapContainingKey(Matcher<K> keyMatcher) {
43 this.keyMatcher = keyMatcher;
44 }
45
46 @Override
47 public boolean matchesSafely(Map<K, ?> item) {
48 for (K key : item.keySet()) {
49 if (keyMatcher.matches(key)) {
50 return true;
51 }
52 }
53 return false;
54 }
55
56 @Override
57 public void describeTo(Description description) {
58 description.appendText("map with key ")
59 .appendDescriptionOf(keyMatcher);
60 }
61
62 public static <K> Matcher<Map<K, ?>> hasKey(K key) {
63 return hasKey(equalTo(key));
64 }
65
66 public static <K> Matcher<Map<K, ?>> hasKey(Matcher<K> keyMatcher) {
67 return new IsMapContainingKey<K>(keyMatcher);
68 }
69 }