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

io.github.olib963.javatest.matchers.internal.PredicateMatcher Maven / Gradle / Ivy

There is a newer version: 0.2.0
Show newest version
package io.github.olib963.javatest.matchers.internal;

import io.github.olib963.javatest.matchers.MatchResult;
import io.github.olib963.javatest.matchers.Matcher;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;

public class PredicateMatcher implements Matcher {
    private final Predicate predicate;
    private final String expected;
    private final Function> mismatchDescriptionFunction;

    private PredicateMatcher(
            Predicate predicate,
            String expected,
            Function> mismatchDescriptionFunction) {
        this.predicate = predicate;
        this.expected = expected;
        this.mismatchDescriptionFunction = mismatchDescriptionFunction;
    }

    public static  Matcher of(Predicate predicate, String expected) {
        return new PredicateMatcher<>(predicate, expected, a -> Optional.empty());
    }

    public static  Matcher of(Predicate predicate, String expected, Function mismatchDescriptionFunction) {
        return new PredicateMatcher<>(predicate, expected, mismatchDescriptionFunction.andThen(Optional::of));
    }

    @Override
    public MatchResult matches(A value) {
        if(predicate.test(value)) {
            return MatchResult.match();
        } else {
            return mismatchDescriptionFunction.apply(value)
                    .map(MatchResult::mismatch)
                    .orElseGet(MatchResult::mismatch);
        }
    }

    @Override
    public String describeExpected() {
        return expected;
    }


    public static  Matcher isEqualTo(A expected) {
        return of(expected::equals, "be equal to {" + expected + "}");
    }

    public static  Matcher hasType(Class expectedClass) {
        return of(
                expectedClass::isInstance,
                "be an instance of {" + expectedClass.getName() + "}",
                value -> "was instead of type {" + value.getClass().getName() + "}"
        );
    }

    public static  Matcher isTheSameInstanceAs(A instance) {
        return of(o -> instance == o, "be the same in memory reference as {" + instance + "}");
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy