Created
June 27, 2014 12:22
-
-
Save GuiSim/e1d1cde0ab66302ae45c to your computer and use it in GitHub Desktop.
Hamcrest matcher that matches a Lambda.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
This looks awesome! Can you show an example use case? I'm not sure how and where to plug in this matcher. Thanks!