|
| 1 | +package testsupport.matchers; |
| 2 | + |
| 3 | +import org.hamcrest.BaseMatcher; |
| 4 | +import org.hamcrest.Description; |
| 5 | + |
| 6 | +import java.util.Iterator; |
| 7 | + |
| 8 | +import static java.util.Arrays.asList; |
| 9 | + |
| 10 | +public class IterableMatcher<Element> extends BaseMatcher<Iterable<Element>> { |
| 11 | + |
| 12 | + private final Iterable<Element> expected; |
| 13 | + |
| 14 | + public IterableMatcher(Iterable<Element> expected) { |
| 15 | + this.expected = expected; |
| 16 | + } |
| 17 | + |
| 18 | + @Override |
| 19 | + public boolean matches(Object actual) { |
| 20 | + return actual instanceof Iterable && iteratesExpectedElementsInOrder((Iterable) actual); |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + public void describeTo(Description description) { |
| 25 | + description.appendValue(expected); |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public void describeMismatch(Object item, Description description) { |
| 30 | + if (item instanceof Iterable) |
| 31 | + description.appendText("was ").appendText(stringify((Iterable) item)); |
| 32 | + else |
| 33 | + super.describeMismatch(item, description); |
| 34 | + } |
| 35 | + |
| 36 | + private boolean iteratesExpectedElementsInOrder(Iterable actual) { |
| 37 | + Iterator actualIterator = actual.iterator(); |
| 38 | + Iterator expectedIterator = expected.iterator(); |
| 39 | + |
| 40 | + while (actualIterator.hasNext() && expectedIterator.hasNext()) |
| 41 | + if (!actualIterator.next().equals(expectedIterator.next())) |
| 42 | + return false; |
| 43 | + |
| 44 | + return actualIterator.hasNext() == expectedIterator.hasNext(); |
| 45 | + } |
| 46 | + |
| 47 | + private String stringify(Iterable iterable) { |
| 48 | + StringBuilder stringBuilder = new StringBuilder().append("<["); |
| 49 | + Iterator iterator = iterable.iterator(); |
| 50 | + while (iterator.hasNext()) { |
| 51 | + stringBuilder.append(iterator.next()); |
| 52 | + if (iterator.hasNext()) |
| 53 | + stringBuilder.append(", "); |
| 54 | + } |
| 55 | + return stringBuilder.append("]>").toString(); |
| 56 | + } |
| 57 | + |
| 58 | + public static <Element> IterableMatcher<Element> iterates(Element... elements) { |
| 59 | + return new IterableMatcher<Element>(asList(elements)); |
| 60 | + } |
| 61 | +} |
0 commit comments