1/*
2 * Copyright (c) 2016 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.matchers.text;
6
7import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
8import static org.mockito.internal.util.StringUtil.decamelizeMatcher;
9
10import java.lang.reflect.Method;
11import org.mockito.ArgumentMatcher;
12
13/**
14 * Provides better toString() text for matcher that don't have toString() method declared.
15 */
16class MatcherToString {
17
18    /**
19     * Attempts to provide more descriptive toString() for given matcher.
20     * Searches matcher class hierarchy for toString() method. If it is found it will be used.
21     * If no toString() is defined for the matcher hierarchy,
22     * uses decamelized class name instead of default Object.toString().
23     * This way we can promote meaningful names for custom matchers.
24     *
25     * @param matcher
26     * @return
27     */
28    static String toString(ArgumentMatcher<?> matcher) {
29        Class<?> cls = matcher.getClass();
30        while(cls != Object.class) {
31            Method[] methods = cls.getDeclaredMethods();
32            for (Method m : methods) {
33                if(isToStringMethod(m)) {
34                    return matcher.toString();
35                }
36            }
37            cls = cls.getSuperclass();
38        }
39        return decamelizeMatcher(matcher.getClass().getSimpleName());
40    }
41
42
43}
44