• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.hamcrest.collection;
2 
3 import org.hamcrest.Description;
4 import org.hamcrest.Matcher;
5 import org.hamcrest.TypeSafeMatcher;
6 
7 import java.util.Arrays;
8 
9 import static org.hamcrest.core.IsEqual.equalTo;
10 
11 /**
12  * Matches if an array contains an item satisfying a nested matcher.
13  */
14 public class IsArrayContaining<T> extends TypeSafeMatcher<T[]> {
15     private final Matcher<? super T> elementMatcher;
16 
IsArrayContaining(Matcher<? super T> elementMatcher)17     public IsArrayContaining(Matcher<? super T> elementMatcher) {
18         this.elementMatcher = elementMatcher;
19     }
20 
21     @Override
matchesSafely(T[] array)22     public boolean matchesSafely(T[] array) {
23         for (T item : array) {
24             if (elementMatcher.matches(item)) {
25                 return true;
26             }
27         }
28         return false;
29     }
30 
31     @Override
describeMismatchSafely(T[] item, Description mismatchDescription)32     public void describeMismatchSafely(T[] item, Description mismatchDescription) {
33         super.describeMismatch(Arrays.asList(item), mismatchDescription);
34     }
35 
36     @Override
describeTo(Description description)37     public void describeTo(Description description) {
38         description
39             .appendText("an array containing ")
40             .appendDescriptionOf(elementMatcher);
41     }
42 
43     /**
44      * Creates a matcher for arrays that matches when the examined array contains at least one item
45      * that is matched by the specified <code>elementMatcher</code>.  Whilst matching, the traversal
46      * of the examined array will stop as soon as a matching element is found.
47      * For example:
48      * <pre>assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))</pre>
49      *
50      * @param elementMatcher
51      *     the matcher to apply to elements in examined arrays
52      */
hasItemInArray(Matcher<? super T> elementMatcher)53     public static <T> Matcher<T[]> hasItemInArray(Matcher<? super T> elementMatcher) {
54         return new IsArrayContaining<T>(elementMatcher);
55     }
56 
57     /**
58      * A shortcut to the frequently used <code>hasItemInArray(equalTo(x))</code>.
59      * For example:
60      * <pre>assertThat(hasItemInArray(x))</pre>
61      * instead of:
62      * <pre>assertThat(hasItemInArray(equalTo(x)))</pre>
63      *
64      * @param element
65      *     the element that should be present in examined arrays
66      */
hasItemInArray(T element)67     public static <T> Matcher<T[]> hasItemInArray(T element) {
68         Matcher<? super T> matcher = equalTo(element);
69         return IsArrayContaining.<T>hasItemInArray(matcher);
70     }
71 }
72