关于dubbo:dubbo-test

14次阅读

共计 1918 个字符,预计需要花费 5 分钟才能阅读完成。

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>

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。

正文完
 0