Spring Boot、Dubbo项目Mock测试踩坑与总结

简介: 本文是对Spring Boot、Dubbo项目进行Mock测试的总结与踩坑实录。搜索了一圈,居然没发现类似的文章,莫非用Dubbo的朋友们都不Mock测试,或者有其他的办法测试吗?简单总结了一下,希望对大家能有一定参考意义。

本文是对Spring Boot、Dubbo项目进行Mock测试的总结与踩坑实录。

搜索了一圈,居然没发现类似的文章,莫非用Dubbo的朋友们都不Mock测试,或者有其他的办法测试吗?

简单总结了一下,希望对大家能有一定参考意义。如果有更好的测试方法,请联系我的邮箱eacdy0000@126.com ,帮忙告知一下。

背景

手上有个整合了Dubbo的Spring Boot应用,在应用中需要消费其他服务的API。由于我依赖的服务并不由我所在的项目组维护(对方可能接口中途会发生变化,甚至,有时候可能并未启动)。

集成测试成本略高,故而想办法Mock测试。以RemoteApi为例,这是一个远程的API。我这一侧(消费者)的代码如下:

@Service
public class MyApi {
    @Reference
    private RemoteApi remoteApi;

    public String hold() {
        return remoteApi.hold();
    }
}
AI 代码解读

由代码可知,MyApi调用了一个远程的API RemoteApi。

下面我们来mock测试。

整合powermock

经过调研,笔者选择powermock作为项目的mock工具。

  1. 加依赖:

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.6.6</version>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.6.6</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-rule</artifactId>
        <version>1.6.6</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-classloading-xstream</artifactId>
        <version>1.6.6</version>
        <scope>test</scope>
    </dependency>
    
    AI 代码解读
  2. 测试启动类:

    @SpringBootApplication
    public class ConsumerTest {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerTest.class, args);
        }
    
        @Bean
        public RemoteApi RemoteApi() {
            RemoteApi remoteApi = PowerMockito.mock(RemoteApi.class);
            PowerMockito.when(remoteApi.hold())
                    .thenAnswer(t -> "我是Mock的API。");
            return remoteApi;
        }
    }
    
    AI 代码解读

    由代码可知,我在这里mock了一个RemoteApi,当调用Mock的RemoteApi.hold()方法时,返回

    我是Mock的API。
    
    AI 代码解读

  3. 测试类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = ConsumerTest.class)
    public class MyApiTest {
        @Autowired
        public MyApi myApi;
    
        @Test
        public void hold() {
            Assert.assertEquals("我是Mock的API。", this.myApi.hold());
        }
    }
    
    AI 代码解读
  4. 执行单元测试,发现Mock并没有成功,Dubbo依然会尝试调用远程API,而并非笔者Mock的RemoteApi。

分析

Mock没有成功,为什么呢?我们不妨将测试类代码修改成如下:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ConsumerTest.class)
public class MyApiTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Before
    public void before() {
        MyApi myApi = applicationContext.getBean(MyApi.class);
        RemoteApi fromMyApi = myApi.getRemoteApi();
        RemoteApi fromSpring = applicationContext.getBean(RemoteApi.class);
        System.out.println("MyApi中注入的RemoteApi是:" + fromMyApi);
        System.out.println("Spring容器中注入的RemoteApi是:" + fromSpring);
    }

    @Autowired
    public MyApi myApi;

    @Test
    public void hold() {
        Assert.assertEquals("我是Mock的API。", this.myApi.hold());
    }
}
AI 代码解读

从代码不难发现,我在执行单元测试之前,分别打印MyApi对象中注入的RemoteApi,以及Spring容器中的RemoteApi(@Bean所注解的方法,new出来的对象,必然在Spring容器中)。

执行后,打印结果如下:

MyApi中注入的RemoteApi是:com.alibaba.dubbo.common.bytecode.proxy0@541afb85
Spring容器中注入的RemoteApi是:remoteApi
AI 代码解读

由打印结果可知,MyApi中注入的RemoteApi和容器中的RemoteApi,压根不是一个实例。

由该结果,可以知道2点:

  1. Dubbo的@Reference注解拿到的一个代理;
  2. @Reference生成的代理并不在Spring容器中(如果Dubbo的Reference的代理也是容器中,那么容器中应该有2个RemoteApi实例,那么调用getBean()应当报错);

解决

原因我们知道了,要如何解决呢?答案很简单——如果我们在执行单元测试之前,将StoreApi中注入的RemoteApi换成Spring容器中的实例(即我们Mock的那个对象),那么问题就可以得到就解决。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ConsumerTest.class)
public class MyApiTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Before
    public void before() {
        MyApi myApi = applicationContext.getBean(MyApi.class);
        RemoteApi fromSpring = applicationContext.getBean(RemoteApi.class);
        myApi.setRemoteApi(fromSpring);
    }

    @Autowired
    public MyApi myApi;

    @Test
    public void hold() {
        Assert.assertEquals("我是Mock的API。", this.myApi.hold());
    }
}
AI 代码解读

再次执行,就会发现,现在已经可以正常Mock了。

源码分析

以上已经提供了解决方案。那么,@Reference注解究竟干了哪些事情呢?我们不妨分析一下。搜索@Reference注解被哪些地方使用,可找到以下代码:com.alibaba.dubbo.config.spring.AnnotationBean#postProcessBeforeInitialization 。以该代码是我们定位问题的入口,由此,我们可以定位到以下两个方法:

  1. com.alibaba.dubbo.config.ReferenceConfig#init
  2. com.alibaba.dubbo.config.ReferenceConfig#createProxy

其中,

  1. createProxy方法用于创建代理对象;

  2. init方法用来判断是否已经初始化,如果没有初始化,就会调用createProxy创建代理对象。过程比较简单,不贴了。

了解Dubbo如何创建对象后,我们来看看Dubbo是如何将代理对象设置到MyApi的,如下图。

dubbo-source.png

分析至此,大家应该能够了解原因了——

  1. @Reference创建了一个代理;
  2. Dubbo自身做了一些判断,如果发现没有初始化,就会创建一个代理;
  3. postProcessBeforeInitialization 方法中,从Spring容器中拿到MyApi对象,并将这个代理对象设到MyApi实例中。

Going Far

我们已经知道,是@Reference注解搞的鬼,除了以上解决方案,还可以弄一个类,转一下。

即:原调用链:

MyApi —> RemoteApi

改为:

MyApi —> 一个转换的类,啥都不干,用了@Service注解,在里面调用RemoteApi的方法 —> RemoteApi

WHATS MORE OVER

如果使用xml配置,不存在该问题,可以很简单地Mock。

配套代码

https://github.com/itmuch/spring-boot-dubbo-mock-sample

本文链接: http://www.itmuch.com/dubbo/spring-boot-dubbo-mock/
**版权声明: **本博客由周立创作,采用 CC BY 3.0 CN 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

目录
打赏
0
0
0
0
29
分享
相关文章
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
61 7
基于SpringBoot+Vue实现的大学生体质测试管理系统设计与实现(系统源码+文档+数据库+部署)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
54 2
Spring Boot 如何测试打包部署
本文介绍了 Spring Boot 项目的开发、调试、打包及投产上线的全流程。主要内容包括: 1. **单元测试**:通过添加 `spring-boot-starter-test` 包,使用 `@RunWith(SpringRunner.class)` 和 `@SpringBootTest` 注解进行测试类开发。 2. **集成测试**:支持热部署,通过添加 `spring-boot-devtools` 实现代码修改后自动重启。 3. **投产上线**:提供两种部署方案,一是打包成 jar 包直接运行,二是打包成 war 包部署到 Tomcat 服务器。
50 10
【Spring项目】表白墙,留言板项目的实现
本文主要介绍了表白墙项目的实现,包含前端和后端代码,以及测试
【Spring】——SpringBoot项目创建
SpringBoot项目创建,SpringBootApplication启动类,target文件,web服务器,tomcat,访问服务器
springboot之SpringBoot单元测试
本文介绍了Spring和Spring Boot项目的单元测试方法,包括使用`@RunWith(SpringJUnit4ClassRunner.class)`、`@WebAppConfiguration`等注解配置测试环境,利用`MockMvc`进行HTTP请求模拟测试,以及如何结合Spring Security进行安全相关的单元测试。Spring Boot中则推荐使用`@SpringBootTest`注解简化测试配置。
167 4
详解Swagger:Spring Boot中的API文档生成与测试工具
详解Swagger:Spring Boot中的API文档生成与测试工具
139 4
使用Spring Boot编写测试用例:实践与最佳实践
使用Spring Boot编写测试用例:实践与最佳实践
190 0
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
101 2

热门文章

最新文章