dubbo如何测试?
和spring齐全一样。
其实就是基于2个注解。
一个是springboot的注解:@SpringBootTest。
一个是spring的注解:@RunWith(SpringRunner.class)。
这两个都是测试相干的注解,而且都在测试jar里。
外围代码
测试代码示例
import lombok.extern.slf4j.Slf4j;import org.apache.dubbo.spring.boot.sample.provider.bootstrap.DubboRegistryZooKeeperProviderBootstrap;import org.apache.dubbo.spring.boot.sample.provider.service.DefaultDemoService;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;/** * @author javaself */@Slf4j@RunWith(SpringRunner.class) //应用junit4@SpringBootTest( classes = DubboRegistryZooKeeperProviderBootstrap.class, //指定启动入口类 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public class DubboTest { @Autowired DefaultDemoService defaultDemoService; //注入dubbo服务 @Test public void test() throws Exception { String s = defaultDemoService.sayHello("Hello, world!"); //调用dubbo服务进行测试 log.info(s); }}
外围步骤
- 创立测试类
- 在测试类上,加2个注解
- pom文件增加依赖的测试jar
- 运行测试类的测试方法
就像个别的测试类的测试方法一样。
@SpringBootTest注解
能够指定一些配置,比方classes属性是指定springboot我的项目的启动入口类。
依赖的测试jar
次要是springboot和spring,还有junit
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> </dependency>
zk
在application.properties增加禁止注册配置,禁止本地服务注册到zk,防止影响测试环境。
# 用于自测,禁止注册到zkdubbo.registry.register=false
多个测试类
如果有多个测试类,能够把公共的局部独立进去。
具体来说,就是写一个根底测试类。
@RunWith(SpringRunner.class)@SpringBootTest( classes = xxx.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)public abstract class BaseTest {}
而后,其余具体的业务测试类,继承它。
这样,就不须要每个业务测试类,都要写一遍反复的注解代码。
总结
外围步骤就是下面讲的。
骨架代码实现之后,前面就是间接注入bean,就能够测试bean。
就像一般的spring bean一样。
测试dubbo服务和一般的spring bean没有任何区别,因为dubbo服务也是spring容器里的bean。