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


}
相关推荐
.格子衫.4 小时前
Spring Boot 原理篇
java·spring boot·后端
多云几多4 小时前
Yudao单体项目 springboot Admin安全验证开启
java·spring boot·spring·springbootadmin
Jabes.yang7 小时前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
聪明的笨猪猪7 小时前
Java Redis “高可用 — 主从复制”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
兮动人7 小时前
Spring Bean耗时分析工具
java·后端·spring·bean耗时分析工具
MESSIR227 小时前
Spring IOC(控制反转)中常用注解
java·spring
摇滚侠7 小时前
Spring Boot 3零基础教程,Demo小结,笔记04
java·spring boot·笔记
笨手笨脚の8 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式
spencer_tseng8 小时前
Eclipse 4.7 ADT (Android Development Tools For Eclipse)
android·java·eclipse
聪明的笨猪猪9 小时前
Java Spring “AOP” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试