if (isFinalJavaSystemClass(type) && !isStatic) { mock = Whitebox.newInstance(type); DefaultFieldValueGenerator.fillWithDefaultValues(mock);
public static <T> T fillWithDefaultValues(T object) { if (object == null) { throw new IllegalArgumentException("object to fill cannot be null"); } Set<Field> allInstanceFields = Whitebox.getAllInstanceFields(object); for (Field field : allInstanceFields) { final Class<?> fieldType = field.getType(); Object defaultValue = TypeUtils.getDefaultValue(fieldType); if (defaultValue == null && fieldType != object.getClass() && !field.isSynthetic()) { defaultValue = instantiateFieldType(field); if (defaultValue != null) { fillWithDefaultValues(defaultValue); } } try { field.set(object, defaultValue); } catch (Exception e) { throw new RuntimeException("Internal error: Failed to set field.", e); } } return object; }
private static Object instantiateFieldType(Field field) { Class<?> fieldType = field.getType(); Object defaultValue; int modifiers = fieldType.getModifiers(); if(fieldType.isAssignableFrom(ClassLoader.class) || isClass(fieldType)) { defaultValue = null; } else if (Modifier.isAbstract(modifiers) && !Modifier.isInterface(modifiers) && !fieldType.isArray()) { Class<?> createConcreteSubClass = new ConcreteClassGenerator().createConcreteSubClass(fieldType); defaultValue = createConcreteSubClass == null ? null : Whitebox.newInstance(createConcreteSubClass); } else { fieldType = substituteKnownProblemTypes(fieldType); defaultValue = Whitebox.newInstance(fieldType); } return defaultValue; }
private <T> T doCreateMock(final Class<T> type, final boolean isStatic, final boolean isSpy, final Object delegatorCandidate, final MockSettings mockSettings, final Method[] methods) { final Class<T> typeToMock = getMockType(type); final Object delegator = isSpy && delegatorCandidate == null ? new Object() : delegatorCandidate; final MockData<T> mockData = createMethodInvocationControl(typeToMock, methods, delegator, mockSettings); T mock = mockData.getMock(); if (isFinalJavaSystemClass(type) && !isStatic) { mock = Whitebox.newInstance(type); DefaultFieldValueGenerator.fillWithDefaultValues(mock); } putMethodInvocationControlToRepository(type, isStatic, mockData, mock); return mock; }