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;
    }


}
相关推荐
ybq195133454311 小时前
Redis-主从复制-分布式系统
java·数据库·redis
weixin_472339461 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
小毛驴8502 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
DKPT2 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
好奇的菜鸟4 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
DuelCode5 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
优创学社25 小时前
基于springboot的社区生鲜团购系统
java·spring boot·后端
幽络源小助理5 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
猴哥源码5 小时前
基于Java+springboot 的车险理赔信息管理系统
java·spring boot
YuTaoShao6 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展