SpringBootTest测试框架三

feign调用mock

注入feign调用的拦截器,自定义InvocationHandlerFactory,重写代理类的实现。

java 复制代码
  @Bean
    public Feign.Builder feignBuilder() {
        return Feign.builder().invocationHandlerFactory((target, dispatch) -> new FeignResultInvocationHandler(target, dispatch));
    }
java 复制代码
public class FeignResultInvocationHandler implements InvocationHandler {
    public static final Logger logger = LoggerFactory.getLogger(FeignResultInvocationHandler.class);

    private final Target target;
    private final Map<Method, InvocationHandlerFactory.MethodHandler> dispatch;

    public FeignResultInvocationHandler(Target target, Map<Method, InvocationHandlerFactory.MethodHandler> dispatch) {
        this.target = checkNotNull(target, "target");
        this.dispatch = checkNotNull(dispatch, "dispatch for %s", target);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("equals".equals(method.getName())) {
            try {
                Object otherHandler =
                        args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
                return equals(otherHandler);
            } catch (IllegalArgumentException e) {
                return false;
            }
        } else if ("hashCode".equals(method.getName())) {
            return hashCode();
        } else if ("toString".equals(method.getName())) {
            return toString();
        }
        // 以上eauals、hashCode等方法需要复制过来,要不然会因方法名问题影响文件的读取
        String methodName = getMethodName(method);

        Type returnType = method.getGenericReturnType();

        Function<String, Object> mockFunction = filePath -> getMockReturnType(filePath, returnType);

        Function remoteFunction = s -> {
            try {
                return dispatch.get(method).invoke(args);
            } catch (Throwable e) {
                logger.error("methodName={} feign remote error", methodName, e);
                throw new RuntimeException(e);
            }
        };

        Object result = TestFileHelper.getResult(methodName, mockFunction, remoteFunction);

        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (obj instanceof FeignResultInvocationHandler) {
            FeignResultInvocationHandler other = (FeignResultInvocationHandler) obj;
            return target.equals(other.target);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return target.hashCode();
    }

    @Override
    public String toString() {
        return target.toString();
    }


    private String getMethodName(Method method) {
        String className = method.getDeclaringClass().getName();
        return className.substring(className.lastIndexOf(".") + 1) + "_" + method.getName();
    }


    public Object getMockReturnType(String filePath, Type type) {
        String result = TestFileHelper.readFile(filePath);
        if (type == null) {
            return result;
        }

        try {
        	// com.google.gson.Gson就是比fastjson好用,这里按类型转换使用Gson非常简单
            Object obj = new Gson().fromJson(result, type);
            return obj;
        }catch (Exception e){
            logger.error("getMockReturnType error", e);
            e.printStackTrace();
        }


        return result;
    }


}
相关推荐
平凡的小码农11 分钟前
JAVA实现大写金额转小写金额
java·开发语言
一直在进步的派大星14 分钟前
Docker 从安装到实战
java·运维·docker·微服务·容器
老华带你飞18 分钟前
公寓管理系统|SprinBoot+vue夕阳红公寓管理系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·课程设计
我明天再来学Web渗透28 分钟前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法
结衣结衣.42 分钟前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
原野心存1 小时前
java基础进阶知识点汇总(1)
java·开发语言
无理 Java1 小时前
【技术详解】SpringMVC框架全面解析:从入门到精通(SpringMVC)
java·后端·spring·面试·mvc·框架·springmvc
gobeyye2 小时前
spring loC&DI 详解
java·spring·rpc
鱼跃鹰飞2 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试
我是浮夸2 小时前
MyBatisPlus——学习笔记
java·spring boot·mybatis