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

at.willhaben.willtest.matcher.ExceptionMatcher Maven / Gradle / Ivy

There is a newer version: 3.1.10
Show newest version
package at.willhaben.willtest.matcher;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.Optional;

/**
 * Matches a given exception type with an optional additional message matcher.
 * @param  expected exception type
 */
@Deprecated
public class ExceptionMatcher extends TypeSafeMatcher{
    private final Matcher messageMatcher;
    private final Class expectedType;

    /**
     * Will match {@link Throwable} instances of the given type. See also {@link TypeSafeMatcher} for details.
     * @param expectedType expected child class of {@link Throwable}
     */
    public ExceptionMatcher(Class expectedType) {
        this(expectedType,null);
    }

    /**
     * Will match {@link Throwable} instances of the given type and if its message matches the given String {@link Matcher}.
     * See also {@link TypeSafeMatcher} for details.
     * @param expectedType expected child class of {@link Throwable}
     * @param messageMatcher matcher for exception message
     */
    public ExceptionMatcher(Class expectedType, Matcher messageMatcher) {
        super(expectedType);
        this.expectedType = expectedType;
        this.messageMatcher = messageMatcher;
    }

    @Override
    protected boolean matchesSafely(T item) {
        return Optional
                .ofNullable(messageMatcher)
                .map(matcher -> matcher.matches(item.getMessage()))
                .orElse(true);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText( "Expected a " + expectedType.getClass().getName() + " instance" );
        if ( messageMatcher != null ) {
            description.appendText( " having a message, which matches: " );
            messageMatcher.describeTo(description);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy