org.hamcrest.collection.IsArrayContaining Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hamcrest-library Show documentation
Show all versions of hamcrest-library Show documentation
A library of Hamcrest matchers - deprecated, please use "hamcrest" instead
package org.hamcrest.collection;
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* Matches if an array contains an item satisfying a nested matcher.
*/
public class IsArrayContaining extends TypeSafeMatcher {
private final Matcher super T> elementMatcher;
public IsArrayContaining(Matcher super T> elementMatcher) {
this.elementMatcher = elementMatcher;
}
@Override
public boolean matchesSafely(T[] array) {
for (T item : array) {
if (elementMatcher.matches(item)) {
return true;
}
}
return false;
}
@Override
public void describeMismatchSafely(T[] item, Description mismatchDescription) {
super.describeMismatch(Arrays.asList(item), mismatchDescription);
};
@Override
public void describeTo(Description description) {
description
.appendText("an array containing ")
.appendDescriptionOf(elementMatcher);
}
/**
* Creates a matcher for arrays that matches when the examined array contains at least one item
* that is matched by the specified elementMatcher
. Whilst matching, the traversal
* of the examined array will stop as soon as a matching element is found.
*
* For example:
* assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))
*
* @param elementMatcher
* the matcher to apply to elements in examined arrays
*/
@Factory
public static Matcher hasItemInArray(Matcher super T> elementMatcher) {
return new IsArrayContaining(elementMatcher);
}
/**
* A shortcut to the frequently used hasItemInArray(equalTo(x))
.
*
* For example:
* assertThat(hasItemInArray(x))
* instead of:
* assertThat(hasItemInArray(equalTo(x)))
*
* @param element
* the element that should be present in examined arrays
*/
@Factory
public static Matcher hasItemInArray(T element) {
Matcher super T> matcher = equalTo(element);
return IsArrayContaining.hasItemInArray(matcher);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy