Skip to content

Instantly share code, notes, and snippets.

@GuiSim
Created June 27, 2014 12:22
Show Gist options
  • Select an option

  • Save GuiSim/e1d1cde0ab66302ae45c to your computer and use it in GitHub Desktop.

Select an option

Save GuiSim/e1d1cde0ab66302ae45c to your computer and use it in GitHub Desktop.
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
Copy Markdown

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
Copy Markdown

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