Skip to content

Instantly share code, notes, and snippets.

Embed
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;
}
@Override
public boolean matches(Object argument)
{
return matcher.apply((T) argument);
}
@Override
public void describeTo(Description description)
{
description.appendText(this.description);
}
}
@bitops
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!

@fobbyal
Copy link

fobbyal commented Oct 30, 2017

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

vs

 assertThat(collection.stream().map(a -> 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