
ext.test4j.hamcrest.collection.IsArrayContaining Maven / Gradle / Ivy
package ext.test4j.hamcrest.collection;
import java.util.Arrays;
import ext.test4j.hamcrest.Description;
import ext.test4j.hamcrest.Factory;
import ext.test4j.hamcrest.Matcher;
import ext.test4j.hamcrest.TypeSafeMatcher;
import static ext.test4j.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);
};
public void describeTo(Description description) {
description
.appendText("an array containing ")
.appendDescriptionOf(elementMatcher);
}
/**
* Evaluates to true if any item in an array satisfies the given matcher.
*/
@Factory
public static Matcher hasItemInArray(Matcher super T> elementMatcher) {
return new IsArrayContaining(elementMatcher);
}
/**
* This is a shortcut to the frequently used hasItemInArray(equalTo(x)).
*
* For example, assertThat(hasItemInArray(equal_to(x)))
* vs. assertThat(hasItemInArray(x))
*/
@Factory
public static Matcher hasItemInArray(T element) {
Matcher super T> matcher = equalTo(element);
return IsArrayContaining.hasItemInArray(matcher);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy