protected List<ConversionStrategy<?>> createConversionStrategies(Properties configuration, String propertyName) { List<String> conversionStrategyClassNames = getStringList(propertyName, configuration); List<ConversionStrategy<?>> conversionStrategies = new ArrayList<ConversionStrategy<?>>(conversionStrategyClassNames.size()); for (String conversionStrategyClassName : conversionStrategyClassNames) { ConversionStrategy<?> conversionStrategy = createInstanceOfType(conversionStrategyClassName, false); conversionStrategies.add(conversionStrategy); } return conversionStrategies; } }
public static void injectIntoAnnotatedFields(Object objectToInject, Object target, Class<? extends Annotation> annotation) { Set<Field> annotatedFields = AnnotationUtils.getFieldsAnnotatedWith(target.getClass(), annotation); for (Field annotatedField : annotatedFields) { setFieldValue(target, annotatedField, objectToInject); } }
protected Object getTarget(Object test, Field field) { Object target = getFieldValue(test, field); if (target instanceof ObjectToInjectHolder<?>) { target = ((ObjectToInjectHolder<?>) target).getObjectToInject(); } return target; }
/** * @return The default {@link DataSetLoadStrategy} class as configured in unitils */ protected DataSetLoadStrategy getDefaultDataSetLoadStrategy() { Class<? extends DataSetLoadStrategy> dataSetLoadStrategyClassName = getClassWithName(getAnnotationPropertyDefault(DbUnitModule.class, DataSet.class, "loadStrategy", configuration)); return createInstanceOfType(dataSetLoadStrategyClassName, false); }
protected Class<?> getMockedClass(Field field) { try { Type type = getGenericType(field); return getClassForType(type); } catch (UnitilsException e) { throw new UnitilsException("Unable to determine type of mock. A mock should be declared using the generic Mock<YourTypeToMock> or PartialMock<YourTypeToMock> types. Field: " + field, e); } }
/** * Checks whether the given argument value is a value of a field in the test object and, if so, returns the * name of that field. * * @param testObject The test instance, null if there is no test object * @param value The value to look for, not null * @return The field name, null if no field was found for the value */ protected String getFieldName(Object testObject, Object value) { if (testObject == null) { return null; } Set<Field> fields = getAllFields(testObject.getClass()); for (Field field : fields) { Object fieldValue = getFieldValue(testObject, field); if (value == fieldValue) { return field.getName(); } } return null; }
Set<Field> fieldsWithExactType = getFieldsOfType(targetClass, objectToInjectType, isStatic); if (fieldsWithExactType.size() > 1) { StringBuilder message = new StringBuilder("More than one " + (isStatic ? "static " : "") + "field with type " + objectToInjectType + " found in " + targetClass.getSimpleName() + "."); Set<Field> fieldsOfType = getFieldsAssignableFrom(targetClass, objectToInjectType, isStatic); if (fieldsOfType.size() == 0) { throw new UnitilsException("No " + (isStatic ? "static " : "") + "field with (super)type " + objectToInjectType + " found in " + targetClass.getSimpleName()); oldValue = getFieldValue(target, fieldToInjectTo); setFieldValue(target, fieldToInjectTo, objectToInject); return oldValue;
/** * Creates an objects of the given fields' declared type and assigns it to this field on the given testObject * * @param testObject The test instance, not null * @param testedObjectField The tested object field, not null */ protected void createObjectForField(Object testObject, Field testedObjectField) { Class<?> declaredClass = testedObjectField.getType(); if (declaredClass.isInterface()) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getType().getSimpleName() + " which is an interface type. It is not automatically instantiated."); } else if (isAbstract(declaredClass.getModifiers())) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getDeclaringClass().getSimpleName() + " which is an abstract class. It is not automatically instantiated."); } else { try { declaredClass.getDeclaredConstructor(); Object instance = createInstanceOfType(declaredClass, true); setFieldValue(testObject, testedObjectField, instance); } catch (NoSuchMethodException e) { logger.warn("Field " + testedObjectField.getName() + " (annotated with @TestedObject) has type " + testedObjectField.getDeclaringClass().getSimpleName() + " which has no default (parameterless) constructor. It is not automatically instantiated."); } } }
/** * Sets the given value on the static property of the given targetClass * * @param targetClass The class on which the static property value should be set * @param staticProperty The name of the property (simple name, not a composite expression) * @param value The value to set */ private static void setValueStatic(Class<?> targetClass, String staticProperty, Object value) { Method staticSetter = ReflectionUtils.getSetter(targetClass, staticProperty, true); if (staticSetter != null) { try { invokeMethod(targetClass, staticSetter, value); } catch (InvocationTargetException e) { throw new UnitilsException("Exception thrown by target", e); } } else { Field staticField = getFieldWithName(targetClass, staticProperty, true); if (staticField == null) { throw new UnitilsException("Static property named " + staticProperty + " not found on class " + targetClass.getSimpleName()); } setFieldValue(targetClass, staticField, value); } } }
/** * * Searches all the fields with the {@link WebPage} annotation and sets the correct elements. * * @param testObject : the testobject. */ public void initElements(Object testObject) { // find fields that has the @WebPage annotation Set<Field> fields = AnnotationUtils.getFieldsAnnotatedWith(testObject.getClass(), WebPage.class); // find the webdriver Set<Field> webdrivers = AnnotationUtils.getFieldsAnnotatedWith(testObject.getClass(), TestWebDriver.class); if (!webdrivers.isEmpty()) { // initialise the page and set the object in the correct field. WebDriver webdriver = ReflectionUtils.getFieldValue(testObject, webdrivers.iterator().next()); for (Field field : fields) { if (webdriver != null) { ReflectionUtils.setFieldValue(testObject, field, getElement(webdriver, field.getType())); } } } else { LOGGER.error("The TestWebDriver cannot be found."); } }
/** * Retrieves the value of the static property from the given class * * @param targetClass The class from which the static property value is retrieved * @param staticProperty The name of the property (simple name, not a composite expression) * @return The value of the static property from the given class */ private static Object getValueStatic(Class<?> targetClass, String staticProperty) { Method staticGetter = getGetter(targetClass, staticProperty, true); if (staticGetter != null) { try { return invokeMethod(targetClass, staticGetter); } catch (InvocationTargetException e) { throw new UnitilsException("Exception thrown by target", e); } } else { Field staticField = getFieldWithName(targetClass, staticProperty, true); if (staticField != null) { return getFieldValue(targetClass, staticField); } else { throw new UnitilsException("Static property named " + staticProperty + " not found on class " + targetClass.getSimpleName()); } } }
protected void createAndInjectMocksIntoTest(Object testObject) { Set<Field> mockFields = getFieldsOfType(testObject.getClass(), Mock.class, false); for (Field field : mockFields) { Mock<?> mock = getFieldValue(testObject, field); if (mock != null) { mock.resetBehavior(); continue; } mock = createMock(testObject, field.getName(), getMockedClass(field)); injectMock(testObject, field, mock); } }
Set<Method> settersWithExactType = getSettersOfType(targetClass, objectToInjectType, isStatic); if (settersWithExactType.size() > 1) { throw new UnitilsException("More than one " + (isStatic ? "static " : "") + "setter with type " + objectToInjectType + " found in " + targetClass.getSimpleName()); Set<Method> settersOfType = getSettersAssignableFrom(targetClass, objectToInjectType, isStatic); if (settersOfType.size() == 0) { throw new UnitilsException("No " + (isStatic ? "static " : "") + "setter with (super)type " + objectToInjectType + " found in " + targetClass.getSimpleName()); Method getter = getGetter(setterToInjectTo, isStatic); if (getter == null) { logger.warn("Unable to retrieve current value of field to inject into, no getter found for setter: " + setterToInjectTo + ". Will not be able to restore value after injection."); } else { oldValue = invokeMethod(target, getter); invokeMethod(target, setterToInjectTo, objectToInject);
/** * Finds a method using the ASM method node * * @param methodNode The ASM method node, not null * @return The method, null if not found */ protected Method getMethod(MethodInsnNode methodNode) { String internalClassName = methodNode.owner; String className = internalClassName.replace('/', '.'); String methodName = methodNode.name; String methodDescriptor = methodNode.desc; Class<?> clazz = getClassWithName(className); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (methodName.equals(method.getName()) && methodDescriptor.equals(getMethodDescriptor(method))) { return method; } } return null; }
@Override protected void postProcessConfiguration(Configuration config) throws HibernateException { if (customConfigMethod != null) { try { ReflectionUtils.invokeMethod(testObject, customConfigMethod, config); } catch (InvocationTargetException e) { throw new UnitilsException("Error while invoking custom config method", e.getCause()); } } }
/** * Auto-injects the fieldToInject by trying to match the fields declared type with a property of the target class. * The target is either an explicitly specified target field of the test, or the field that is annotated with * {@link TestedObject} * * @param test The instance to inject into, not null * @param fieldToAutoInjectStatic The field from which the value is injected into the target, not null */ protected void injectStaticByType(Object test, Field fieldToAutoInjectStatic) { InjectIntoStaticByType injectIntoStaticByTypeAnnotation = fieldToAutoInjectStatic.getAnnotation(InjectIntoStaticByType.class); Class<?>[] targetClass = injectIntoStaticByTypeAnnotation.target(); Object objectToInject = getObjectToInject(test, fieldToAutoInjectStatic); Type objectToInjectType = getObjectToInjectType(test, fieldToAutoInjectStatic); Class objectToInjectClass = getClassForType(objectToInjectType); Restore restore = getEnumValueReplaceDefault(InjectIntoStaticByType.class, "restore", injectIntoStaticByTypeAnnotation.restore(), defaultAnnotationPropertyValues); PropertyAccess propertyAccess = getEnumValueReplaceDefault(InjectIntoStaticByType.class, "propertyAccess", injectIntoStaticByTypeAnnotation.propertyAccess(), defaultAnnotationPropertyValues); try { for (Class<?> clzz : targetClass) { Object oldValue = InjectionUtils.injectIntoStaticByType(objectToInject, objectToInjectType, clzz, propertyAccess); storeValueToRestoreAfterTest(clzz, null, objectToInjectClass, propertyAccess, oldValue, restore); } } catch (UnitilsException e) { throw new UnitilsException(getSituatedErrorMessage(InjectIntoStaticByType.class, fieldToAutoInjectStatic, e.getMessage()), e); } }
protected void createAndInjectPartialMocksIntoTest(Object testObject) { Set<Field> partialMockFields = getFieldsOfType(testObject.getClass(), PartialMock.class, false); for (Field field : partialMockFields) { Mock<?> mock = getFieldValue(testObject, field); if (mock != null) { mock.resetBehavior(); continue; } mock = createPartialMock(testObject, field.getName(), getMockedClass(field)); injectMock(testObject, field, mock); } }
/** * Gets all the field values in the given test object with their corresponding field names. * * @param testedObject The test object * @return The values and names in an identity map, empty if tested object is null */ protected Map<Object, String> getFieldValuesAndNames(Object testedObject) { Map<Object, String> result = new IdentityHashMap<Object, String>(); if (testedObject == null) { return result; } Set<Field> fields = getAllFields(testedObject.getClass()); for (Field field : fields) { Object value = getFieldValue(testedObject, field); if (value != null) { result.put(value, field.getName()); } } return result; }
public static StackTraceElement[] getInvocationStackTrace(Class<?> invokedInterface, boolean included) { StackTraceElement[] currentStackTrace = Thread.currentThread().getStackTrace(); for (int i = currentStackTrace.length - 1; i >= 0; i--) { String className = currentStackTrace[i].getClassName(); Class<?> clazz; try { clazz = getClassWithName(className); } catch (UnitilsException e) { // unable to load class, this should never happen for the class we are looking for continue; } if (invokedInterface.isAssignableFrom(clazz) || isProxyClassName(className)) { int index = included ? i : i + 1; return getStackTraceStartingFrom(currentStackTrace, index); } } return null; }
/** * Calls all {@link AfterCreateMock} annotated methods on the test, passing the given mock. * These annotated methods must have following signature <code>void myMethod(Object mock, String name, Class type)</code>. * If this is not the case, a runtime exception is called. * * @param testObject the test, not null * @param mockObject the mock, not null * @param name the field(=mock) name, not null */ protected void callAfterCreateMockMethods(Object testObject, Mock<?> mockObject, String name) { Set<Method> methods = getMethodsAnnotatedWith(testObject.getClass(), AfterCreateMock.class); for (Method method : methods) { try { invokeMethod(testObject, method, mockObject, name, ((MockObject<?>) mockObject).getMockedType()); } catch (InvocationTargetException e) { throw new UnitilsException("An exception occurred while invoking an after create mock method.", e); } catch (Exception e) { throw new UnitilsException("Unable to invoke after create mock method. Ensure that this method has following signature: void myMethod(Object mock, String name, Class type)", e); } } }