org.itsallcode.matcher.auto.OptionalMatchers Maven / Gradle / Ivy
package org.itsallcode.matcher.auto;
import java.util.Optional;
import org.hamcrest.*;
/**
* Provides a set of Hamcrest matchers for {@code java.util.Optional}:
*
* - {@link #isEmpty()} - matches when the examined {@code Optional} contains
* no value.
* - {@link #isPresentAnd(Matcher)} - matches when the examined
* {@code Optional} contains a value that satisfies the specified matcher.
*
*
* This was copied from
* {@link https://github.com/npathai/hamcrest-optional/blob/master/src/main/java/com/github/npathai/hamcrestopt/OptionalMatchers.java}
*
* @author npathai, sweiler
*/
class OptionalMatchers {
/**
* Creates a matcher that matches when the examined {@code Optional} contains no
* value.
*
*
* Optional<String> optionalObject = Optional.empty();
* assertThat(optionalObject, isEmpty());
*
*
* @return a matcher that matches when the examined {@code Optional} contains no
* value.
*/
@SuppressWarnings("java:S1452") // Generic wildcard required here
static Matcher> isEmpty() {
return new EmptyMatcher();
}
private static class EmptyMatcher extends TypeSafeMatcher> {
public void describeTo(final Description description) {
description.appendText("is ");
}
@Override
protected boolean matchesSafely(final Optional> item) {
return !item.isPresent();
}
@Override
protected void describeMismatchSafely(final Optional> item, final Description mismatchDescription) {
mismatchDescription.appendText("had value ");
mismatchDescription.appendValue(item.orElseThrow());
}
}
/**
* Creates a matcher that matches when the examined {@code Optional} contains a
* value that satisfies the specified matcher.
*
*
* Optional<String> optionalObject = Optional.of("dummy value");
* assertThat(optionalObject, isPresentAnd(startsWith("dummy")));
*
*
* @param matcher a matcher for the value of the examined {@code Optional}.
* @param the class of the value.
* @return a matcher that matches when the examined {@code Optional} contains a
* value that satisfies the specified matcher.
*/
static Matcher> isPresentAnd(final Matcher super T> matcher) {
return new HasValue<>(matcher);
}
private static class HasValue extends TypeSafeMatcher> {
private final Matcher super T> matcher;
public HasValue(final Matcher super T> matcher) {
this.matcher = matcher;
}
@Override
public void describeTo(final Description description) {
description.appendText("has value that is ");
matcher.describeTo(description);
}
@Override
protected boolean matchesSafely(final Optional item) {
return item.isPresent() && matcher.matches(item.get());
}
@Override
protected void describeMismatchSafely(final Optional item, final Description mismatchDescription) {
if (item.isPresent()) {
mismatchDescription.appendText("value ");
matcher.describeMismatch(item.get(), mismatchDescription);
} else {
mismatchDescription.appendText("was ");
}
}
}
// This is an utility class that must not be instantiated.
private OptionalMatchers() {
}
}