1 package org.hamcrest.collection; 2 3 import org.hamcrest.FeatureMatcher; 4 import org.hamcrest.Matcher; 5 6 import static org.hamcrest.core.DescribedAs.describedAs; 7 import static org.hamcrest.core.IsEqual.equalTo; 8 9 /** 10 * Matches if array size satisfies a nested matcher. 11 */ 12 public class IsArrayWithSize<E> extends FeatureMatcher<E[], Integer> { 13 public IsArrayWithSize(Matcher<? super Integer> sizeMatcher) { 14 super(sizeMatcher, "an array with size","array size"); 15 } 16 17 @Override 18 protected Integer featureValueOf(E[] actual) { 19 return actual.length; 20 } 21 22 /** 23 * Creates a matcher for arrays that matches when the <code>length</code> of the array 24 * satisfies the specified matcher. 25 * For example: 26 * <pre>assertThat(new String[]{"foo", "bar"}, arrayWithSize(equalTo(2)))</pre> 27 * 28 * @param sizeMatcher 29 * a matcher for the length of an examined array 30 */ 31 public static <E> Matcher<E[]> arrayWithSize(Matcher<? super Integer> sizeMatcher) { 32 return new IsArrayWithSize<E>(sizeMatcher); 33 } 34 35 /** 36 * Creates a matcher for arrays that matches when the <code>length</code> of the array 37 * equals the specified <code>size</code>. 38 * For example: 39 * <pre>assertThat(new String[]{"foo", "bar"}, arrayWithSize(2))</pre> 40 * 41 * @param size 42 * the length that an examined array must have for a positive match 43 */ 44 public static <E> Matcher<E[]> arrayWithSize(int size) { 45 return arrayWithSize(equalTo(size)); 46 } 47 48 /** 49 * Creates a matcher for arrays that matches when the <code>length</code> of the array 50 * is zero. 51 * For example: 52 * <pre>assertThat(new String[0], emptyArray())</pre> 53 * 54 */ 55 public static <E> Matcher<E[]> emptyArray() { 56 Matcher<E[]> isEmpty = arrayWithSize(0); 57 return describedAs("an empty array", isEmpty); 58 } 59 } 60