Created
March 21, 2015 00:02
OptionalWithValue - Hamcrest matcher for values wrapped in Java 8 Optional
This file contains hidden or 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 org.hamcrest.Description; | |
import org.hamcrest.Factory; | |
import org.hamcrest.Matcher; | |
import org.hamcrest.TypeSafeDiagnosingMatcher; | |
import java.util.Optional; | |
import static org.hamcrest.core.IsEqual.equalTo; | |
public class OptionalWithValue<T> extends TypeSafeDiagnosingMatcher<Optional<? extends T>> { | |
@Factory | |
public static <T> Matcher<Optional<? extends T>> optionalWithValue(Matcher<? super T> valueMatcher) { | |
return new OptionalWithValue<>(valueMatcher); | |
} | |
@Factory | |
public static <T> Matcher<Optional<? extends T>> optionalWithValue(T value) { | |
return optionalWithValue(equalTo(value)); | |
} | |
private final Matcher<? super T> subMatcher; | |
public OptionalWithValue(Matcher<? super T> subMatcher) { | |
this.subMatcher = subMatcher; | |
} | |
@Override | |
protected boolean matchesSafely(Optional<? extends T> item, Description mismatchDescription) { | |
if (!item.isPresent()) { | |
mismatchDescription.appendText("an empty optional"); | |
return false; | |
} | |
boolean matches = subMatcher.matches(item.get()); | |
if (!matches) { | |
subMatcher.describeMismatch(item.get(), mismatchDescription); | |
} | |
return matches; | |
} | |
@Override | |
public void describeTo(Description description) { | |
description.appendText("optional with value "); | |
subMatcher.describeTo(description); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment