From c54ff0e71fd2e97202ab800b9d3b6e35478f819b Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Wed, 13 Nov 2013 22:15:37 +0100 Subject: [PATCH] Add matchers for iterators. --- src/test/java/net/pterodactylus/sone/Matchers.java | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/src/test/java/net/pterodactylus/sone/Matchers.java b/src/test/java/net/pterodactylus/sone/Matchers.java index 4bf7aa5..c08ffb1 100644 --- a/src/test/java/net/pterodactylus/sone/Matchers.java +++ b/src/test/java/net/pterodactylus/sone/Matchers.java @@ -17,8 +17,15 @@ package net.pterodactylus.sone; +import static java.util.Arrays.asList; import static java.util.regex.Pattern.compile; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.google.common.base.Objects; +import com.google.common.collect.Lists; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; @@ -44,4 +51,65 @@ public class Matchers { }; } + public static Matcher> contains(T... items) { + return contains(asList(items)); + } + + public static Matcher> contains(final Collection items) { + return new TypeSafeMatcher>() { + @Override + protected boolean matchesSafely(Iterator iterator) { + for (T item : items) { + if (!iterator.hasNext()) { + return false; + } + T nextItem = iterator.next(); + if (!Objects.equal(item, nextItem)) { + return false; + } + } + if (iterator.hasNext()) { + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("contains ").appendValue(items); + } + }; + } + + public static Matcher> containsInAnyOrder(T... items) { + return containsInAnyOrder(asList(items)); + } + + public static Matcher> containsInAnyOrder(final Collection items) { + return new TypeSafeMatcher>() { + private final List remainingItems = Lists.newArrayList(items); + @Override + protected boolean matchesSafely(Iterator iterator) { + while (iterator.hasNext()) { + T item = iterator.next(); + if (remainingItems.isEmpty()) { + return false; + } + if (!remainingItems.remove(item)) { + return false; + } + } + if (!remainingItems.isEmpty()) { + return false; + } + return true; + } + + @Override + public void describeTo(Description description) { + description.appendText("contains ").appendValue(items); + } + }; + } + } -- 2.7.4