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);
}
}
}
}
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;
}
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);
}
}
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;
}
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);
}
}
}
Aggregations