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

org.hamcrest.collection.IsArrayContaining Maven / Gradle / Ivy

There is a newer version: 3.0
Show newest version
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 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);
    };

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy