unruly / java-8-matchers Goto Github PK
View Code? Open in Web Editor NEWHamcrest Matchers for Java 8 features
License: MIT License
Hamcrest Matchers for Java 8 features
License: MIT License
There is a space character missing in the description of OptionalMatchers.contains(Matcher<T> matcher)
before the description of the sub-matcher.
import org.junit.Test;
import java.util.Optional;
import static co.unruly.matchers.OptionalMatchers.contains;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class OptionalMatcherTest {
@Test
public void show_the_bug() {
assertThat(Optional.of("foo"), contains(equalTo("bar")));
}
}
This produces the following message:
java.lang.AssertionError:
Expected: Optional with an item that matches"bar"
but: was <Optional[foo]>
Expected :Optional with an item that matches"bar"
Actual :<Optional[foo]>
This gets very confusing when using a FeatureMatcher because the FeatureMatcher does not quote its description so it just becomes something like
Expected: Optional with an item that matchesbar
which can be pretty hard to read.
This one works:
assertThat(Stream.of(7, 3, 1, 4, 1), anyMatch(greaterThan(5)));
but now... there is another requirement!!!
The stream must not contain any zeros.
So I tried:
assertThat(Stream.of(7, 3, 1, 4, 1),
both(allMatch(is(not(0))))
.and(anyMatch(greaterThan(5))));
which fails with IllegalStateException: stream has already been operated upon or closed
Seems that the both
matcher causes the stream to be operated twice.
Other issue? Anyway to overcome this?
I'm looking for something like IsCollectionContaining.<T>hasItems(items);
so that I can write
assertThat(items.stream().map(/*some mapping*/)), hasItems("item1", "item2"));
instead of
assertThat(items.stream().map(/*some mapping*/).collect(Collectors.toList()), hasItems("item1", "item2"));
This code works, for example, but needs a describeTo that isn't rubbish ...
@Test
public void shouldBeAbleToBuildAMatcherUsingALambda() throws Exception {
List<String> strings = Arrays.asList("one", "two");
assertThat(strings, with(l -> l.get(0), equalTo("one")));
}
private <U,V> Matcher<U> with(Function<U,V> transform, Matcher<V> matcher){
return new TypeSafeMatcher<U>() {
@Override
protected boolean matchesSafely(U item) {
return matcher.matches(transform.apply(item));
}
@Override
public void describeTo(Description description) {
description.appendText("a Object that matches")
.appendDescriptionOf(matcher)
.appendText("after being transformed");
}
};
}
Basic idea, add a method with the signature:
public static <I, O> Matcher<I> where(DescribableFunction<? super I, O> property, Function<I, Matcher<? super O>> matcher);
So you could write:
assertThat(someList, where(String::toUpperCase, str -> equalTo(str)));
my actual use case is a bit more complex than this.
Plans for a 1.5 release anytime soon? ๐
I think it would be better if StreamMatchers.empty()
and StreamMatchers.equalTo()
returned Matcher<S>
, this would make them usable with a wider range of methods (in particular, methods that expect a Stream<T>
argument).
A Stream may contain nulls
(though whether that's a good idea is up for debate ;) ), but StreamMatchers.contains(..)
is not null safe. A workaround is to collect the steam to e.g. a List and use Hamcrest's Matchers.contains(..)
, which handles expected null-elements. The workaround also demonstrates that StreamMatchers.contains(..)
should indeed handle null-elements.
The sollution is simple. Just replace the nextExpected.equals(nextActual)
(https://github.com/unruly/java-8-matchers/blob/master/src/main/java/co/unruly/matchers/StreamMatchers.java#L650) with java.util.Objects.equals(nextExpected, nextActual)
, and it handles expected null-elements.
I have implemented the fix with testcase that I will issue a pull request for.
Thanks for making the library!
Hello,
I was wondering if this project is maintained, as there seems to not be that much activity going on. There are some old issues, and a couple of pull-requests just lying around.
I think this is a very useful library, and I actively use it on a daily basis, so I am wondering about what are the possibilities of me to become a maintainer of this repository, as opposed to be working on my own fork and send pull-requests? The last merged pull-request was mine, and approved by @mrwilson , so I am shamelessly mentioning you to maybe provide som insights on this matter :)
For reference, this is my previous contributions to this library:
I honestly hadn't noticed we don't support this before:
assertThat(
Stream.of("one", "two", "three"),
StreamMatchers.contains(equalTo("one"), equalTo("two"), equalTo("three"))
);
We're relying on the toString to give meaningful errors, which works ok while the thing that's being wrapped has a nice toString implementation, but fails horribly when it doesn't, even if the matcher being passed in returns a nice message ...
int[] wanted = { 1, 2, 3};
int[] got = {2,3,4};
@Test
public void shouldBeDiagnosing() throws Exception {
StringDescription mismatchDescription = new StringDescription();
arrayMatcher(wanted).describeMismatch(got, mismatchDescription);
assertThat(mismatchDescription.toString(), is("[<2>, <3>, <4>]"));
}
@Test
public void optionalMatchersShouldAlsoBeSelfDiagnosing() throws Exception {
StringDescription mismatchDescription = new StringDescription();
OptionalMatchers.contains(arrayMatcher(wanted)).describeMismatch(Optional.of(got), mismatchDescription);
assertThat(mismatchDescription.toString(), is("an Optional with an item [<2>, <3>, <4>]"));
}
private TypeSafeDiagnosingMatcher<int[]> arrayMatcher(int ... expected) {
return new TypeSafeDiagnosingMatcher<int[]>() {
@Override
public void describeTo(Description description) {
description
.appendText("an int array equal to ")
.appendValue(expected);
}
@Override
protected boolean matchesSafely(int[] item, Description mismatchDescription) {
boolean matches = Arrays.equals(expected, item);
if(!matches) {
mismatchDescription.appendValue(item);
}
return matches;
}
};
}
Currently, we cannot match an Optional<List<String>>
against Hamcrest's hasItems
matcher, which matches against Optional<Iterable<? super String>
.
We can support matching against a generic type that extends that of the matcher.
public static <T, S extends T> Matcher<Optional<S>> containsFlex(Matcher<T> matcher) {
return new TypeSafeMatcher<Optional<S>>() {
@Override
protected boolean matchesSafely(Optional<S> item) {
return item.map(matcher::matches).orElse(false);
}
@Override
public void describeTo(Description description) {
description.appendText("Optional with an item that matches" + matcher);
}
};
}
Integrating with Travis CI will allow us to run tests automatically and make merging pull requests simpler.
We already do this for junit-rules if you need an example.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.