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

org.test4j.mock.Stubs Maven / Gradle / Ivy

package org.test4j.mock;

import org.test4j.mock.props.FakeProperties;
import org.test4j.mock.stub.Impostor;
import org.test4j.mock.stub.ProxyInvokable;

import java.lang.annotation.Annotation;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * 对类进行代理加强
 *
 * @author wudarui
 */
@SuppressWarnings({"unchecked", "rawtypes", "UnusedReturnValue"})
public class Stubs {
    private Stubs() {
    }

    /**
     * 创建stub对象, 并且调用定义好的Mock方法
     *
     * @param aClass class
     * @param     type
     * @return ignore
     */
    public static  T fake(Class aClass) {
        return Impostor.fake(aClass);
    }

    /**
     * 创建stub对象, 并且调用定义好的Mock方法
     *
     * @param aClass class
     * @param args   constructor args
     * @param     type
     * @return ignore
     */
    public static  T fake(Class aClass, Object... args) {
        return Impostor.fake(aClass, args);
    }

    /**
     * @param invokable  ProxyInvokable
     * @param baseType   class
     * @param interfaces interface list
     * @param         type
     * @return ignore
     */
    public static  T proxy(ProxyInvokable invokable, Class baseType, Class... interfaces) {
        return Impostor.proxy(invokable, baseType, interfaces);
    }

    /**
     * 将对象空属性stub赋值
     *
     * @param target 赋值对象
     */
    public static  O nilFields(O target, Class... aClasses) {
        return nilFields(target, false, aClasses);
    }

    /**
     * 将对象空属性stub赋值
     *
     * @param target    赋值对象
     * @param recursive 是否对设置的属性进行递归处理
     */
    public static  O nilFields(O target, boolean recursive, Class... aClasses) {
        Queue queue = new LinkedList<>();
        queue.offer(target);
        while (!queue.isEmpty()) {
            Object obj = queue.poll();
            Map objs;
            try {
                if (aClasses == null || aClasses.length == 0) {
                    objs = new FakeProperties(obj).fakeNullProperties();
                } else {
                    objs = new FakeProperties(obj).fakeNullByAnnotation(aClasses);
                }
            } catch (Throwable e) {
                objs = null;
            }
            if (recursive && objs != null) {
                objs.entrySet().stream()
                    .filter(entry -> !entry.getKey().contains("$"))
                    .forEach(entry -> queue.offer(entry.getValue()));
            }
        }
        return target;
    }
}