AbstractCollectionMatcher extends AbstractSimpleMatcher { @Override protected final boolean matches(Parameter parameter, Object actual, Object property) { if (property == null) { throw new InvalidArgumentException("Comparison property cannot be null: " + parameter.getPath()); } final Collection collection; if (property.getClass().isArray()) { collection = new LinkedList(); for (int i = 0; i < Array.getLength(property); i++) { final Object item = Array.get(property, i); collection.add(item); } } else if (property instanceof Iterator) { collection = new LinkedList(); final Iterator iterator = (Iterator) property; while (iterator.hasNext()) { collection.add(iterator.next()); } } else if (property instanceof Iterable) { collection = new LinkedList(); for (Object item : ((Iterable) property)) { collection.add(item); } } else { throw new InvalidArgumentException("Expected an array, an iterator, or an iterable object"); } return matches(actual, collection); }  @Override boolean isApplicableTo(Class<?> parameterType, Class<?>... propertiesTypes);  }
@Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = "Comparison property cannot be null: xyz") public void testWhenPivotIsNull() { new SpyingCollectionMatcher().matches(new ImmutableParameter("xyz", null, null, null), 1, new Object[]{null}); }
@Test public void testPassingInAnArray() { final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); matcher.matches(null, null, new Object[]{new Object[]{1, 2, 3, 4}}); assertThat(matcher.getCollection(), is(notNullValue())); assertThat(matcher.getCollection(), hasSize(4)); assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); }
@Test public void testPassingInAnIterator() { final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); matcher.matches(null, null, new Object[]{Arrays.asList(1, 2, 3, 4).iterator()}); assertThat(matcher.getCollection(), is(notNullValue())); assertThat(matcher.getCollection(), hasSize(4)); assertThat(matcher.getCollection(), contains(1, 2, 3, 4)); }
@Test public void testPassingInAnIterable() { final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher(); matcher.matches(null, null, new Object[]{new HashSet<>(Arrays.asList(1, 2, 3, 4))}); assertThat(matcher.getCollection(), is(notNullValue())); assertThat(matcher.getCollection(), hasSize(4)); assertThat(matcher.getCollection(), containsInAnyOrder(1, 2, 3, 4)); }
@Test(expectedExceptions = InvalidArgumentException.class, expectedExceptionsMessageRegExp = "Expected an array, an iterator, or an iterable object") public void testPassingInAnythingElse() { new SpyingCollectionMatcher().matches(null, null, new Object[]{new Object()}); }