-
Notifications
You must be signed in to change notification settings - Fork 379
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Request: Lambda Matcher #300
Comments
I'd love to get better support for lamdas and other Java 8 features into Hamcrest. At the moment, Hamcrest 1.x works with Java 5 and greater, Hamcrest 2.x works with Java 7 and greater. For this feature, we'd have to increase the minimum supported version to Java 8. Issues #206 and #207 discuss various ways we might go about doing that, though we haven't made much progress against those issues yet. I think this feature would have to depend upon those issues being completed first. |
You can try to use hamcrest-more-matchers (available on maven central). Your sample will look like import static com.github.seregamorph.hamcrest.MoreMatchers.where;
@Test
public void test() {
List<Item> list = Arrays.asList(new Item()
.setStringElem("el-non-match")
.setLongElem(2L));
assertThat(list, hasItem(allOf(
where(Item::getStringElem, is("el1")),
where(Item::getLongElem, is(2L)))));
}
public static class Item {
private String stringElem;
private long longElem;
public String getStringElem() {
return stringElem;
}
public long getLongElem() {
return longElem;
}
public Item setStringElem(String stringElem) {
this.stringElem = stringElem;
return this;
}
public Item setLongElem(long longElem) {
this.longElem = longElem;
return this;
}
} Please note, the failed message will have convenient diagnostics (method reference resolved as string): after call Item.getStringElem
It works not only in Java 8, but also in Java 11 and 14. |
Thanks, switched to hamcrest.MoreMatchers.where. Works like a charm |
Create a matcher that takes a lambda as type safe replacement of
Matchers.hasProperty(propertyName, valueMatcher)
Sample code:
Usage:
The text was updated successfully, but these errors were encountered: