aboutsummaryrefslogtreecommitdiff
path: root/hamcrest-library/src/main/java/org/hamcrest/collection/IsArrayContaining.java
blob: 76ddf9d86f82a0e3a4ffd57a951905f2fbe0b193 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package org.hamcrest.collection;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;
import static org.hamcrest.core.IsEqual.equalTo;

public class IsArrayContaining<T> extends TypeSafeMatcher<T[]> {

    private final Matcher<T> elementMatcher;

    public IsArrayContaining(Matcher<T> elementMatcher) {
        this.elementMatcher = elementMatcher;
    }

    public boolean matchesSafely(T[] array) {
        for (T item : array) {
            if (elementMatcher.matches(item)) {
                return true;
            }
        }
        return false;
    }

    public void describeTo(Description description) {
        description
        	.appendText("an array containing ")
        	.appendDescriptionOf(elementMatcher);
    }

    @Factory
    public static <T> Matcher<T[]> hasItemInArray(Matcher<T> elementMatcher) {
        return new IsArrayContaining<T>(elementMatcher);
    }

    @Factory
    public static <T> Matcher<T[]> hasItemInArray(T element) {
        return hasItemInArray(equalTo(element));
    }

}