aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/zwobble/couscous/tests/util/ExtraMatchers.java
blob: 3107d53feb0c1954b68f13e3ebf5bc8fb0dd2cc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package org.zwobble.couscous.tests.util;

import org.hamcrest.Description;
import org.hamcrest.DiagnosingMatcher;
import org.hamcrest.Matcher;

public class ExtraMatchers {
    public static <T, U> Matcher<T> isInstance(Class<U> type, Matcher<? super U> downcastMatcher) {
        return new DiagnosingMatcher<T>() {
            @Override
            protected boolean matches(Object item, Description mismatch) {
                if (null == item) {
                    mismatch.appendText("null");
                    return false;
                }

                if (!type.isInstance(item)) {
                    mismatch.appendValue(item).appendText(" is a " + item.getClass().getName());
                    return false;
                }

                if (!downcastMatcher.matches(item)) {
                    downcastMatcher.describeMismatch(item, mismatch);
                    return false;
                }

                return true;
            }

            @Override
            public void describeTo(Description description) {
                description
                    .appendText(type.getSimpleName())
                    .appendText(" with ");
                downcastMatcher.describeTo(description);
            }
        };
    }
}