SpringCloud使用Nacos作为配置中心运行JUnit用例

分享知识 传递快乐

Spingboot 项目的配置方式通常都是在本地 application.yml 中配置,在运行 JUnit 的用例时只要配置没问题基本都可以运行。

作为 SpingCloud 服务如果使用 Nacos 作为配置中心时它的配置文件基本都配置到远程服务器上,如果依然还像 Springboot 的方式运行 JUnit 用例,这是会报不合法的参数异常。原因是使用 Nacos 作为配置中心时绝大多数配置都是配置到远程服务器上,这就导致了程序读取不到远程配置。

解决问题如下:

在运行 JUnit 用例时把运行服务时的参数命令加入到 JUnit 示例中即可。为了更好明白,请参考下面示例。

bootstrap.yml

server:
  port: 8080

spring:
  profiles:
    active: ${spring.profiles.active}
  application:
    name: sync
  cloud:
    nacos:
      username: nacos
      password: ${nacos.password}
      discovery:
        ###nacos注册地址
        server-addr: ${nacos.server}
        enabled: true
      config:
        ###配置中心连接地址
        server-addr: ${nacos.server}
        ###类型
        file-extension: yaml
        ###分组
        group: DEFAULT_GROUP
        shared-configs: application.yaml

java

import cn.hutool.json.JSONUtil;
import com.anchnet.sync.model.AccountEntity;
import com.anchnet.sync.service.AccountService;
import lombok.extern.slf4j.Slf4j;
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;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = SyncCenterApplication.class)
@Slf4j
public class AppDemo2 {

    @Autowired
    private AccountService accountService;

    @Test
    public void getById() {
        AccountEntity entity = accountService.getById(45472);
        System.out.println(JSONUtil.toJsonStr(entity));
    }
}

操作如下:

右击红色框的图标

 选择编辑运行配置

 弹出

修改配置

 保存后,点击运行即可

 

 

—————————
如有不足请留言指正
相互学习,共同进步


版权声明:本文为xhaimail原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。