Search in sources :

Example 1 with MethodNotFoundException

use of org.powermock.reflect.exceptions.MethodNotFoundException in project powermock by powermock.

the class MethodProxy method proxy.

/**
	 * Add a proxy for a method declared in class {@code declaringClass}.
	 * Each call to the method will be routed to the invocationHandler instead.
	 */
public static void proxy(Class<?> declaringClass, String methodName, InvocationHandler invocationHandler) {
    assertInvocationHandlerNotNull(invocationHandler);
    if (declaringClass == null) {
        throw new IllegalArgumentException("declaringClass cannot be null");
    }
    if (methodName == null || methodName.length() == 0) {
        throw new IllegalArgumentException("methodName cannot be empty");
    }
    Method[] methods = Whitebox.getMethods(declaringClass, methodName);
    if (methods.length == 0) {
        throw new MethodNotFoundException(String.format("Couldn't find a method with name %s in the class hierarchy of %s", methodName, declaringClass.getName()));
    } else if (methods.length > 1) {
        throw new TooManyMethodsFoundException(String.format("Found %d methods with name %s in the class hierarchy of %s.", methods.length, methodName, declaringClass.getName()));
    }
    MockRepository.putMethodProxy(methods[0], invocationHandler);
}
Also used : TooManyMethodsFoundException(org.powermock.reflect.exceptions.TooManyMethodsFoundException) Method(java.lang.reflect.Method) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException)

Example 2 with MethodNotFoundException

use of org.powermock.reflect.exceptions.MethodNotFoundException in project powermock by powermock.

the class WhiteboxImpl method getMethods.

/**
     * Get an array of {@link Method}'s that matches the supplied list of method
     * names. Both instance and static methods are taken into account.
     *
     * @param clazz       The class that should contain the methods.
     * @param methodNames Names of the methods that will be returned.
     * @return An array of Method's.
     */
public static Method[] getMethods(Class<?> clazz, String... methodNames) {
    if (methodNames == null || methodNames.length == 0) {
        throw new IllegalArgumentException("You must supply at least one method name.");
    }
    final List<Method> methodsToMock = new LinkedList<Method>();
    Method[] allMethods = null;
    if (clazz.isInterface()) {
        allMethods = getAllPublicMethods(clazz);
    } else {
        allMethods = getAllMethods(clazz);
    }
    for (Method method : allMethods) {
        for (String methodName : methodNames) {
            if (method.getName().equals(methodName)) {
                method.setAccessible(true);
                methodsToMock.add(method);
            }
        }
    }
    final Method[] methodArray = methodsToMock.toArray(new Method[0]);
    if (methodArray.length == 0) {
        throw new MethodNotFoundException(String.format("No methods matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(methodNames), getType(clazz)));
    }
    return methodArray;
}
Also used : Method(java.lang.reflect.Method) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException) LinkedList(java.util.LinkedList)

Example 3 with MethodNotFoundException

use of org.powermock.reflect.exceptions.MethodNotFoundException in project swagger-core by swagger-api.

the class TestUtils method testBuilders.

public static <T> void testBuilders(Class<T> clazz, Set<String> exclusions) throws Exception {
    Map<Field, Object> propertiesAndNonDefaultValues = getPropertiesAndValues(clazz, exclusions, false, true);
    T instance = null;
    try {
        instance = clazz.newInstance();
    } catch (InstantiationException ex) {
        instance = Whitebox.newInstance(clazz);
    }
    for (Field field : propertiesAndNonDefaultValues.keySet()) {
        Method[] methods = {};
        try {
            methods = PowerMockito.methods(instance.getClass(), new String[] { field.getName() });
        } catch (MethodNotFoundException ex) {
            continue;
        }
        for (Method method : methods) {
            if (method.getParameterTypes().length == 1) {
                Object value = propertiesAndNonDefaultValues.get(field);
                if (value != null && method.getParameterTypes()[0].isAssignableFrom(value.getClass())) {
                    T res = Whitebox.invokeMethod(instance, field.getName(), value);
                    assertEquals(Whitebox.getInternalState(res, field.getName()), value, "the value of the field must be the one that has just be set:" + field);
                }
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException)

Example 4 with MethodNotFoundException

use of org.powermock.reflect.exceptions.MethodNotFoundException in project swagger-core by swagger-api.

the class TestUtils method testCommonMethods.

public static <T> void testCommonMethods(Class<T> clazz, Set<String> exclusions) throws Exception {
    T instance = null;
    Constructor<?>[] constructors = PowerMockito.constructorsDeclaredIn(clazz);
    for (Constructor<?> constructor : constructors) {
        Class<?>[] types = constructor.getParameterTypes();
        List<Object> parameters = new ArrayList<Object>();
        for (Class<?> type : types) {
            parameters.add(getTypeNonDefaultValue(type));
        }
        try {
            instance = Whitebox.invokeConstructor(clazz, types, parameters.toArray());
        } catch (Exception exx) {
            LOGGER.log(Level.INFO, exx.getMessage(), exx);
            continue;
        }
    }
    if (instance == null) {
        try {
            instance = clazz.newInstance();
        } catch (InstantiationException ex) {
            LOGGER.log(Level.INFO, ex.getMessage(), ex);
            instance = Whitebox.newInstance(clazz);
        }
    }
    Method[] methods = {};
    try {
        methods = PowerMockito.methodsDeclaredIn(instance.getClass());
    } catch (MethodNotFoundException ex) {
        LOGGER.log(Level.INFO, ex.getMessage(), ex);
    }
    Set<String> commonMethodNames = new HashSet<String>(Arrays.asList("_default", "_enum", "example", "vendorExtension", "setEnum"));
    for (Method method : methods) {
        if (commonMethodNames.contains(method.getName()) && (exclusions == null || !exclusions.contains(method.getName()))) {
            System.out.println("testing common method: " + method);
            List<Object> parameters = new ArrayList<Object>();
            Class<?>[] types = method.getParameterTypes();
            if (types.length <= 2) {
                for (Class<?> type : types) {
                    parameters.add(getTypeNonDefaultValue(type));
                }
            }
            if (method.getName().equals("vendorExtension")) {
                parameters = Arrays.asList((Object) "x-vendor", "value");
            }
            Object[] parametersArray = parameters.toArray();
            String getterMethodName = method.getName();
            if (method.getName().startsWith("set")) {
                getterMethodName = "g" + getterMethodName.substring(1);
            } else {
                if (getterMethodName.startsWith("_"))
                    getterMethodName = getterMethodName.substring(1);
                getterMethodName = "get" + getterMethodName.substring(0, 1).toUpperCase() + getterMethodName.substring(1);
                if (parameters.size() > 1)
                    getterMethodName = getterMethodName + "s";
            }
            Object value = parametersArray[0];
            boolean testWithUnknownString = false;
            if (parameters.size() == 1) {
                Method getMethod = null;
                try {
                    getMethod = PowerMockito.method(clazz, getterMethodName);
                } catch (MethodNotFoundException ex) {
                    LOGGER.log(Level.INFO, ex.getMessage());
                    continue;
                }
                Class<?> retType = getMethod.getReturnType();
                if (value instanceof String && !retType.isAssignableFrom(String.class)) {
                    value = getTypeNonDefaultValue(retType).toString();
                    parametersArray[0] = value;
                    testWithUnknownString = true;
                }
            }
            try {
                Whitebox.setInternalState(instance, "_enum", (Object) null);
            } catch (FieldNotFoundException ex) {
                LOGGER.log(Level.INFO, ex.getMessage());
            }
            Whitebox.invokeMethod(instance, method.getName(), parametersArray);
            Object res = Whitebox.invokeMethod(instance, getterMethodName);
            if (parameters.size() > 1 && res instanceof Map) {
                res = ((Map) res).get(parameters.get(0));
                value = parameters.get(1);
            }
            if (value == null) {
                assertNull(res, "the value returned by " + getterMethodName + " must be null as we set it null through " + method);
            } else if (res instanceof Collection) {
                assertTrue(((Collection) res).contains(value) || res.equals(value), "the value returned by " + getterMethodName + " must contain the value set by " + method);
            } else {
                assertEquals(res.toString(), value.toString(), "the value returned by " + getterMethodName + " must be the same set by " + method);
            }
            if (testWithUnknownString) {
                // try to raise an xxxformatexception
                value = "unknown string";
                parametersArray[0] = value;
                Object actual = Whitebox.invokeMethod(instance, getterMethodName);
                Whitebox.invokeMethod(instance, method.getName(), parametersArray);
                res = Whitebox.invokeMethod(instance, getterMethodName);
                assertEquals(actual, res, "the value must not change when passing an unknown value to " + method);
            }
        }
    }
}
Also used : Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException) Method(java.lang.reflect.Method) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException) Collection(java.util.Collection) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 5 with MethodNotFoundException

use of org.powermock.reflect.exceptions.MethodNotFoundException in project powermock by powermock.

the class WhiteboxImpl method getMethods.

/**
     * Get an array of {@link Method}'s that matches the method name and whose
     * argument types are assignable from {@code expectedTypes}. Both
     * instance and static methods are taken into account.
     *
     * @param clazz                   The class that should contain the methods.
     * @param methodName              Names of the methods that will be returned.
     * @param expectedTypes           The methods must match
     * @param exactParameterTypeMatch {@code true} if the {@code expectedTypes} must match
     *                                the parameter types must match exactly, {@code false} if
     *                                the {@code expectedTypes} are allowed to be converted
     *                                into primitive types if they are of a wrapped type and still
     *                                match.
     * @return An array of Method's.
     */
public static Method[] getMethods(Class<?> clazz, String methodName, Class<?>[] expectedTypes, boolean exactParameterTypeMatch) {
    List<Method> matchingArgumentTypes = new LinkedList<Method>();
    Method[] methods = getMethods(clazz, methodName);
    for (Method method : methods) {
        final Class<?>[] parameterTypes = method.getParameterTypes();
        if (checkIfParameterTypesAreSame(method.isVarArgs(), expectedTypes, parameterTypes) || (!exactParameterTypeMatch && checkIfParameterTypesAreSame(method.isVarArgs(), convertParameterTypesToPrimitive(expectedTypes), parameterTypes))) {
            matchingArgumentTypes.add(method);
        }
    }
    final Method[] methodArray = matchingArgumentTypes.toArray(new Method[0]);
    if (methodArray.length == 0) {
        throw new MethodNotFoundException(String.format("No methods matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(methodName), getType(clazz)));
    }
    return matchingArgumentTypes.toArray(new Method[matchingArgumentTypes.size()]);
}
Also used : Method(java.lang.reflect.Method) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException) LinkedList(java.util.LinkedList)

Aggregations

Method (java.lang.reflect.Method)7 MethodNotFoundException (org.powermock.reflect.exceptions.MethodNotFoundException)7 LinkedList (java.util.LinkedList)3 TooManyMethodsFoundException (org.powermock.reflect.exceptions.TooManyMethodsFoundException)2 Constructor (java.lang.reflect.Constructor)1 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 FieldNotFoundException (org.powermock.reflect.exceptions.FieldNotFoundException)1