All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.test4j.mock.props.FakeProperties Maven / Gradle / Ivy

package org.test4j.mock.props;

import org.test4j.Logger;
import org.test4j.mock.Stubs;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * 将对象属性设置为stub对象
 *
 * @author wudarui
 */
public class FakeProperties {
    private Object target;

    private Class klass;

    public FakeProperties(Object target) {
        if (target == null) {
            throw new RuntimeException("The target object can't be null.");
        }
        this.target = target;
        this.klass = target.getClass();
    }

    /**
     * 对所有空属性进行赋值, 包括父类定义的字段
     */
    public void fakeNullProperties() {
        this.fakeProperties(f -> f.get(target) == null);
    }

    /**
     * 只对定义了对应Annotation注解的空属性stub操作
     *
     * @param annotationClass
     */
    public void fakeNullByAnnotation(Class... annotationClass) {
        this.fakeProperties(f -> {
            if (f.get(target) != null) {
                return false;
            }
            for (Class aClass : annotationClass) {
                if (f.getAnnotation(aClass) != null) {
                    return true;
                }
            }
            return false;
        });
    }

    /**
     * 对符合条件的field进行stub赋值
     *
     * @param predicate
     */
    private void fakeProperties(FieldPredicate predicate) {
        Class aClass = this.klass;
        while (aClass != Object.class) {
            Field[] fields = aClass.getDeclaredFields();
            for (Field field : fields) {
                this.fakeField(field, predicate);
            }
            aClass = aClass.getSuperclass();
        }
    }

    /**
     * 对符合条件的field进行stub赋值
     *
     * @param field
     * @param predicate
     */
    private void fakeField(Field field, FieldPredicate predicate) {
        boolean accessible = field.isAccessible();
        try {
            field.setAccessible(true);
            if (predicate.test(field)) {
                Object stub = Stubs.fake(field.getType());
                field.set(target, stub);
            }
        } catch (Exception e) {
            Logger.warn(e.getMessage());
        } finally {
            field.setAccessible(accessible);
        }
    }

    private interface FieldPredicate {
        boolean test(Field field) throws Exception;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy