Skip to content

@TestPropertySource 注解

  • @TestPropertySource 用于测试类中定义配置,效果仅作用于本测试类
    1. 如果项目使用了配置中心(微服务),且配置中心存在对应的配置,配置中心会覆盖 @TestPropertySource 注解的配置

配置

  1. 假如要添加的配置如下

    properties
    a.host=127.0.0.1
    a.port=6379
    a.database=8
    a.password=xuxiaowei.com.cn
    yaml
    a:
      host: 127.0.0.1
      port: 6379
      database: 8
      password: xuxiaowei.com.cn
  2. yamlproperties 工具:application、bootstrap 配置文件乱码、警告等问题

  3. 测试类代码

java
package cn.com.xuxiaowei.demo;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

@Slf4j
@SpringBootTest
@TestPropertySource(properties = {
        "a.host=127.0.0.1",
        "a.port=12345",
        "a.database=8",
        "a.password=xuxiaowei.com.cn"
})
class DemoApplicationTests {

    @Value("${a.host}")
    private String host;

    @Value("${a.port}")
    private String port;

    @Value("${a.database}")
    private String database;

    @Value("${a.password}")
    private String password;

    @Test
    void contextLoads() {
        log.info("host: {}", host);
        log.info("port: {}", port);
        log.info("database: {}", database);
        log.info("password: {}", password);

        // 日志示例:
        // 2024-05-15T16:44:28.186+08:00  INFO 26820 --- [demo] [           main] c.c.xuxiaowei.demo.DemoApplicationTests  : host: 127.0.0.1
        // 2024-05-15T16:44:28.190+08:00  INFO 26820 --- [demo] [           main] c.c.xuxiaowei.demo.DemoApplicationTests  : port: 12345
        // 2024-05-15T16:44:28.190+08:00  INFO 26820 --- [demo] [           main] c.c.xuxiaowei.demo.DemoApplicationTests  : database: 8
        // 2024-05-15T16:44:28.190+08:00  INFO 26820 --- [demo] [           main] c.c.xuxiaowei.demo.DemoApplicationTests  : password: xuxiaowei.com.cn
    }

}