Skip to content

Instantly share code, notes, and snippets.

@dmcg
Last active June 21, 2019 22:19
Show Gist options
  • Save dmcg/74628586fa79b3a3350f to your computer and use it in GitHub Desktop.
Save dmcg/74628586fa79b3a3350f to your computer and use it in GitHub Desktop.
Nasty hack Hamcrest Stream matcher
public class StreamMatchers {
public static class StreamContainingInAnyOrderMatcher<T> extends DelegatingStreamMatcher<T> {
public StreamContainingInAnyOrderMatcher(T... items) {
super(org.hamcrest.Matchers.arrayContainingInAnyOrder(items), "Stream of ");
}
}
public static class EmptyStreamMatcher<T> extends DelegatingStreamMatcher<T> {
public EmptyStreamMatcher() {
super(Matchers.emptyArray(), "Stream like ");
}
}
public static class DelegatingStreamMatcher<T> extends TypeSafeMatcher<Stream<? extends T>> {
private final Matcher<T[]> delegate;
private final String descriptionPrefix;
private Optional<Object[]> itemsAsArray = Optional.empty();
public DelegatingStreamMatcher(Matcher<T[]> delegate, String descriptionPrefix) {
this.delegate = delegate;
this.descriptionPrefix = descriptionPrefix;
}
@Override
public void describeTo(Description description) {
description.appendText(descriptionPrefix);
delegate.describeTo(description);
}
@Override
protected boolean matchesSafely(Stream<? extends T> item) {
itemsAsArray = Optional.of(item.toArray());
return delegate.matches(itemsAsArray.get());
}
@Override
protected void describeMismatchSafely(Stream<? extends T> item, Description mismatchDescription) {
delegate.describeMismatch(itemsAsArray.get(), mismatchDescription);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment