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

co.unruly.control.matchers.SuccessMatcher Maven / Gradle / Ivy

Go to download

A collection of functional utilities around error handling, wrapping a successfully returned value or error

The newest version!
package co.unruly.control.matchers;

import co.unruly.control.result.Result;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class SuccessMatcher extends TypeSafeDiagnosingMatcher> {

    private final Matcher innerMatcher;

    public SuccessMatcher(Matcher innerMatcher) {
        this.innerMatcher = innerMatcher;
    }

    @Override
    protected boolean matchesSafely(Result result, Description description) {
        Boolean matches = result.either(
            innerMatcher::matches,
            failure -> false
        );

        if(!matches) {
            ResultMatchers.describeTo(result, description);
        }

        return matches;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("A Success containing ");
        innerMatcher.describeTo(description);
    }

    private void describe(Result result, Description description) {
        result.either(
            success -> description.appendText("A Success containing " + success),
            failure -> description.appendText("A Failure containing " + failure)
        );
    }
}