All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ext.test4j.hamcrest.collection.IsArrayContaining Maven / Gradle / Ivy

There is a newer version: 2.5.0
Show newest version
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 elementMatcher;

    public IsArrayContaining(Matcher 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 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 matcher = equalTo(element);
        return IsArrayContaining.hasItemInArray(matcher);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy