dubbo test

2年前 (2022) 程序员胖胖胖虎阿
124 0 0

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


}

核心步骤

  1. 创建测试类
  2. 在测试类上,加2个注解
  3. pom文件添加依赖的测试jar
  4. 运行测试类的测试方法

就像一般的测试类的测试方法一样。

@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>

dubbo test

zk

在application.properties添加禁止注册配置,禁止本地服务注册到zk,避免影响测试环境。

# 用于自测,禁止注册到zk
dubbo.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。

版权声明:程序员胖胖胖虎阿 发表于 2022年10月6日 下午6:48。
转载请注明:dubbo test | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...