Spring Boot Junit动态代理实现Mock方法

说到Spring Boot 单元测试主要有两个主流集成分别是Mockito,Junit,这个各有特点,在实际开发中,我想要的测试框架应该是这个框架集成者。要有Junit能够运行某一个单元用例,完整的项目环境,又需要Mockito能对某一个依赖进行注入,指定返回值内容。可惜实际中这两个框架根本不能同时运行的。突然想到可以通过AOP的环绕通知来实现Mock注入功能,覆盖某一个方法返回值。 现在有一个Feign接口AService,实际情况我们环境根本就没有这个服务,调用这个方法一定会报错的。通过代理技术的环绕通知覆盖返回值,能让方法正常调用。具体代码实现如下

Feign 代码

kotlin 复制代码
@FeignClient(name = "application-a")
public interface AFeignService {

    @RequestMapping("/url/path/get")
    Result<Object> get();
}

测试用例

less 复制代码
@SpringBootTest
@Slf4j
class AFeignServiceTest {

    @Autowired
    private AFeignService aFeignService;

    @Test
    void get() {
        Result<Object> result = aFeignService.get();
        log.info(JSONObject.toJSONString(result));
    }
}

执行测试用例,一定会出错,缺少代理方法 在test中添加代理配置类

less 复制代码
@Aspect
@Slf4j
public class AspConfig {

    @Pointcut("execution(* com..AFeignService.get(..))")
    public void pointcue(){

    }

    @Around("pointcue()")
    public Object overrideReturnValue(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AspConfig.overrideReturnValue execute .................");
        //joinPoint.proceed();  不调用原来方法
        ErpReturnDTO dto = new ErpReturnDTO();
        dto.setStatus(200);
        dto.setSuccess(true);
        dto.setMessage("success");
        dto.setData(new ArrayList<>());
        Result<ErpReturnDTO> result = Result.succeed(dto);
        return result;
    }

}

添加切面配置类,这是用于测试用途的代码,不能写在src/代码上,而是使用ImportBeanDefinitionRegistrar,在测试中引用进来。 ImportBeanDefinitionRegistrar: 是Spring提供接口,运行开发者添加自定义添加自己的配置类,Spring Boot组件扩展就是通过这个接口来实现的。

java 复制代码
public class TestAopImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(AspConfig.class);
        GenericBeanDefinition definition = (GenericBeanDefinition) definitionBuilder.getRawBeanDefinition();
        registry.registerBeanDefinition(AspConfig.class.getName(), definition);
    }

}

在原来的单元测试引入代理配置就可以了

less 复制代码
@SpringBootTest
@Slf4j
@Import(TestAopImportBeanDefinitionRegistrar.class)
class AFeignServiceTest

再次运行测试用例,没有异常,并且返回对象成功打印出来

ruby 复制代码
{"code":0,"data":{"data":[],"message":"success","status":200,"subMessage":"success","success":true},"msg":"操作成功","success":true}

有这个代理配置,就可以在平常的开发中,对单元测试中的依赖进行代理覆盖返回值,达到Mock某个方法的返回值效果了。

相关推荐
钱栈up17 分钟前
删 18 个模块全程零报错:烧结系统单体拆微服务的 P0 实操
spring boot·微服务
软件技术NINI13 小时前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
bs_wa6616 小时前
(赠源码)大学生社团管理系统72638-( java、PHP、python、C#、小程序、硬件、机器学习、大数据分析、深度学习,大屏、文案、毕设等)
java·spring boot·redis·mysql·tomcat·maven·idea
夜雪劍辰18 小时前
Spring Boot Redis 序列化踩坑:一个开关让跨工程全读成 LinkedHashMap
spring boot·redis
计算机–阿拉升学长18 小时前
基于springBool+Vue美食分享平台 — 系统设计与实现
前端·vue.js·spring boot·mysql·vue·javaweb·美食
夜雪轻寒19 小时前
Spring Boot 4 升级 Redis 序列化:编译报 tools.jackson.databind 不存在
spring boot·redis·后端
Rain的Java大神之路2 天前
Spring Boot 4 把自动配置拆成 47 个模块后,我的 `dependency:tree` 翻天了:一份从排查到治理的完整实战手册
java·spring boot·后端
软件技术NINI2 天前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端
软件技术NINI2 天前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
她的男孩2 天前
会签选了候选角色,发起却报 nrOfInstances:Forge Admin 改成按人展开集合
spring boot·低代码·工作流引擎