Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Hamcrest matcher that matches a Lambda.
import java.util.function.Function;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
public class LambdaMatcher<T> extends BaseMatcher<T>
private final Function<T, Boolean> matcher;
private final String description;
public LambdaMatcher(Function<T, Boolean> matcher,
String description)
this.matcher = matcher;
this.description = description;
public boolean matches(Object argument)
return matcher.apply((T) argument);
public void describeTo(Description description)
Copy link

bitops commented Feb 28, 2017

This looks awesome! Can you show an example use case? I'm not sure how and where to plug in this matcher. Thanks!

Copy link

fobbyal commented Oct 30, 2017

assertThat(collection,hasItem(new LambdaMatcher(a -> a.getStr1().equals("abc"),"Str1 should equal Abc")));


 assertThat( -> a.getStr1()).collect(toList()),hasItem(equalTo("abc")));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment