|
| 1 | +package org.hamcrest; |
| 2 | + |
| 3 | +import org.hamcrest.internal.ReflectiveTypeFinder; |
| 4 | + |
| 5 | +/** |
| 6 | + * Supporting class for matching a feature of an object. Uses a given function to extract |
| 7 | + * the feature to be matched against. |
| 8 | + * In preparation for Java 8. |
| 9 | + * |
| 10 | + * @param <T> The type of the object to be matched |
| 11 | + * @param <U> The type of the feature to be matched |
| 12 | + */ |
| 13 | +public class FunctionMatcher<T, U> extends TypeSafeDiagnosingMatcher<T> { |
| 14 | + public static interface Feature<T, U> { |
| 15 | + U from(T actual); |
| 16 | + } |
| 17 | + |
| 18 | + |
| 19 | + private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("featureValueOf", 1, 0); |
| 20 | + private final Matcher<? super U> subMatcher; |
| 21 | + private final String featureDescription; |
| 22 | + private final String featureName; |
| 23 | + private final Feature<T, U> feature; |
| 24 | + |
| 25 | + /** |
| 26 | + * Constructor |
| 27 | + * @param featureDescription Descriptive text to use in describeTo |
| 28 | + * @param featureName Identifying text for mismatch message |
| 29 | + * @param subMatcher The matcher to apply to the feature |
| 30 | + * @param feature A function to extra the value to be matched against. |
| 31 | + */ |
| 32 | + public FunctionMatcher(String featureDescription, String featureName, |
| 33 | + Matcher<? super U> subMatcher, |
| 34 | + Feature<T, U> feature) { |
| 35 | + super(TYPE_FINDER); |
| 36 | + this.subMatcher = subMatcher; |
| 37 | + this.featureDescription = featureDescription; |
| 38 | + this.featureName = featureName; |
| 39 | + this.feature = feature; |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + @Override |
| 44 | + protected boolean matchesSafely(T actual, Description mismatch) { |
| 45 | + final U featureValue = feature.from(actual); |
| 46 | + if (subMatcher.matches(featureValue)) { |
| 47 | + return true; |
| 48 | + } |
| 49 | + |
| 50 | + mismatch.appendText(featureName).appendText(" "); |
| 51 | + subMatcher.describeMismatch(featureValue, mismatch); |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public final void describeTo(Description description) { |
| 57 | + description.appendText(featureDescription).appendText(" ") |
| 58 | + .appendDescriptionOf(subMatcher); |
| 59 | + } |
| 60 | +} |
0 commit comments