Search in sources :

Example 1 with FieldNotFoundException

use of org.powermock.reflect.exceptions.FieldNotFoundException 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 2 with FieldNotFoundException

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

the class WhiteboxImpl method getField.

/**
     * Gets the field.
     *
     * @param fieldName the field name
     * @param where     the where
     * @return the field
     */
private static Field getField(String fieldName, Class<?> where) {
    if (where == null) {
        throw new IllegalArgumentException("where cannot be null");
    }
    Field field = null;
    try {
        field = where.getDeclaredField(fieldName);
        field.setAccessible(true);
    } catch (NoSuchFieldException e) {
        throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName() + ".");
    }
    return field;
}
Also used : Field(java.lang.reflect.Field) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException)

Example 3 with FieldNotFoundException

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

the class WhiteboxImpl method getInternalState.

/**
     * Get the value of a field using reflection. Use this method when you need
     * to specify in which class the field is declared. This might be useful
     * when you have mocked the instance you are trying to access. Use this
     * method to avoid casting.
     *
     * @param <T>       the expected type of the field
     * @param object    the object to modify
     * @param fieldName the name of the field
     * @param where     which class the field is defined
     * @return the internal state
     */
@SuppressWarnings("unchecked")
public static <T> T getInternalState(Object object, String fieldName, Class<?> where) {
    if (object == null || fieldName == null || fieldName.equals("") || fieldName.startsWith(" ")) {
        throw new IllegalArgumentException("object, field name, and \"where\" must not be empty or null.");
    }
    Field field = null;
    try {
        field = where.getDeclaredField(fieldName);
        field.setAccessible(true);
        return (T) field.get(object);
    } catch (NoSuchFieldException e) {
        throw new FieldNotFoundException("Field '" + fieldName + "' was not found in class " + where.getName() + ".");
    } catch (Exception e) {
        throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
    }
}
Also used : Field(java.lang.reflect.Field) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException) MethodInvocationException(org.powermock.reflect.exceptions.MethodInvocationException) TooManyMethodsFoundException(org.powermock.reflect.exceptions.TooManyMethodsFoundException) TooManyFieldsFoundException(org.powermock.reflect.exceptions.TooManyFieldsFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MethodNotFoundException(org.powermock.reflect.exceptions.MethodNotFoundException) ConstructorNotFoundException(org.powermock.reflect.exceptions.ConstructorNotFoundException) TooManyConstructorsFoundException(org.powermock.reflect.exceptions.TooManyConstructorsFoundException) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException)

Example 4 with FieldNotFoundException

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

the class WhiteboxImpl method getFields.

/**
     * Get an array of {@link Field}'s that matches the supplied list of field
     * names. Both instance and static fields are taken into account.
     *
     * @param clazz      The class that should contain the fields.
     * @param fieldNames Names of the fields that will be returned.
     * @return An array of Field's. May be of length 0 but not .
     */
public static Field[] getFields(Class<?> clazz, String... fieldNames) {
    final List<Field> fields = new LinkedList<Field>();
    for (Field field : getAllFields(clazz)) {
        for (String fieldName : fieldNames) {
            if (field.getName().equals(fieldName)) {
                fields.add(field);
            }
        }
    }
    final Field[] fieldArray = fields.toArray(new Field[fields.size()]);
    if (fieldArray.length == 0) {
        throw new FieldNotFoundException(String.format("No fields matching the name(s) %s were found in the class hierarchy of %s.", concatenateStrings(fieldNames), getType(clazz)));
    }
    return fieldArray;
}
Also used : Field(java.lang.reflect.Field) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException) LinkedList(java.util.LinkedList)

Example 5 with FieldNotFoundException

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

the class WhiteboxImpl method copyState.

/**
     * Copy state.
     *
     * @param object   the object
     * @param context  the context
     * @param strategy The field matching strategy.
     */
static void copyState(Object object, Object context, FieldMatchingStrategy strategy) {
    if (object == null) {
        throw new IllegalArgumentException("object to set state cannot be null");
    } else if (context == null) {
        throw new IllegalArgumentException("context cannot be null");
    } else if (strategy == null) {
        throw new IllegalArgumentException("strategy cannot be null");
    }
    Set<Field> allFields = isClass(context) ? getAllStaticFields(getType(context)) : getAllInstanceFields(context);
    for (Field field : allFields) {
        try {
            final boolean isStaticField = Modifier.isStatic(field.getModifiers());
            setInternalState(isStaticField ? getType(object) : object, field.getType(), field.get(context));
        } catch (FieldNotFoundException e) {
            if (strategy == FieldMatchingStrategy.STRICT) {
                throw e;
            }
        } catch (IllegalAccessException e) {
            // Should never happen
            throw new RuntimeException("Internal Error: Failed to get the field value in method setInternalStateFromContext.", e);
        }
    }
}
Also used : Field(java.lang.reflect.Field) FieldNotFoundException(org.powermock.reflect.exceptions.FieldNotFoundException)

Aggregations

FieldNotFoundException (org.powermock.reflect.exceptions.FieldNotFoundException)6 Field (java.lang.reflect.Field)4 MethodNotFoundException (org.powermock.reflect.exceptions.MethodNotFoundException)2 Constructor (java.lang.reflect.Constructor)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Test (org.junit.Test)1 ConstructorNotFoundException (org.powermock.reflect.exceptions.ConstructorNotFoundException)1 MethodInvocationException (org.powermock.reflect.exceptions.MethodInvocationException)1 TooManyConstructorsFoundException (org.powermock.reflect.exceptions.TooManyConstructorsFoundException)1 TooManyFieldsFoundException (org.powermock.reflect.exceptions.TooManyFieldsFoundException)1 TooManyMethodsFoundException (org.powermock.reflect.exceptions.TooManyMethodsFoundException)1 ClassWithInternalState (org.powermock.reflect.testclasses.ClassWithInternalState)1