All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.annimon.stream.test.hamcrest.OptionalMatcher Maven / Gradle / Ivy

There is a newer version: 1.2.2
Show newest version
package com.annimon.stream.test.hamcrest;

import com.annimon.stream.Optional;
import static org.hamcrest.CoreMatchers.is;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class OptionalMatcher {

    private OptionalMatcher() { }

    public static Matcher> isPresent() {
        return new IsPresentMatcher();
    }

    public static Matcher> isEmpty() {
        return new IsEmptyMatcher();
    }

    public static  Matcher> hasValue(T object) {
        return hasValueThat(is(object));
    }

    public static  Matcher> hasValueThat(Matcher matcher) {
        return new HasValueMatcher(matcher);
    }

    public static class IsPresentMatcher extends TypeSafeDiagnosingMatcher> {

        @Override
        protected boolean matchesSafely(Optional optional, Description mismatchDescription) {
            mismatchDescription.appendText("Optional was empty");
            return optional.isPresent();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Optional value should be present");
        }
    }

    public static class IsEmptyMatcher extends TypeSafeDiagnosingMatcher> {

        @Override
        protected boolean matchesSafely(Optional optional, Description mismatchDescription) {
            mismatchDescription.appendText("Optional was present");
            return !optional.isPresent();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Optional value should be empty");
        }
    }

    public static class HasValueMatcher extends TypeSafeDiagnosingMatcher> {

        private final Matcher matcher;

        public HasValueMatcher(Matcher matcher) {
            this.matcher = matcher;
        }

        @Override
        protected boolean matchesSafely(Optional optional, Description mismatchDescription) {
            if (!optional.isPresent()) {
                mismatchDescription.appendText("Optional was empty");
                return false;
            }
            final T value = optional.get();
            mismatchDescription.appendText("Optional value ");
            matcher.describeMismatch(value, mismatchDescription);
            return matcher.matches(value);
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("Optional value ").appendDescriptionOf(matcher);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy