springboot单元测试读取yml文件

本文详细介绍如何在Spring Boot项目中使用Maven进行依赖管理,包括核心启动器、开发工具、Lombok等,并展示了如何通过YAML文件配置复杂的数据结构,如JSON对象和列表。此外,还提供了一个单元测试示例,演示了如何读取和验证这些配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom文件配置

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 支持 @ConfigurationProperties 注解 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.40</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>java-noob</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

yml文件配置

service:
  applyList: [{"fruit":"apple","interest":"hisrory"},{"fruit":"orange","interest":"music"}]

配置类

@Component
@ConfigurationProperties(prefix = "service")
public class Service
{
    @Getter
    @Setter
    private JSONObject bannerPicList = new JSONObject(true);

    @Override
    public String toString()
    {
        return "Service{" +
            "applyList='" + applyList+ '\'' +
            '}';
    }
}

单元测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class JavaNoobApplicationTests
{
    @Autowired
    private Service service;
    
    @Test
    public void contextLoads()
    {
        System.out.println(service);
    }
}

还有要注意的是,从yml文件读取json字符串时,需要在配置类中指定JSONObject类型的,但也可以配置成yml格式的List里面包含map形式的。

### 如何在Spring Boot中使用Apollo进行单元测试 #### 使用`@SpringBootTest`注解启动应用上下文并加载Apollo配置 为了确保在执行单元测试时能够正确加载来自Apollo的配置,在编写测试类时可以利用`@SpringBootTest`注解来指定要使用的主应用程序类。这会触发整个Spring Boot应用上下文的初始化过程,从而使得可以从Apollo获取最新的配置数据。 ```java @SpringBootTest(classes = MySpringbootApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationTests { // 测试逻辑... } ``` 此设置允许测试环境下的应用实例连接到Apollo服务器,并读取相应的配置文件[^3]。 #### 配置Apollo客户端以适应测试需求 为了让Apollo能够在测试期间正常工作,通常需要调整一些默认行为以便更好地模拟生产环境中的情况。可以通过自定义属性或覆盖现有属性的方式实现这一点: - 设置Meta Server地址指向本地运行的服务端; - 修改AppId为特定于测试用途的名字; - 如果适用的话,还可以设定不同的Cluster名称用于区分不同类型的测试场景; 这些更改可以在项目的`application-test.yml`(或其他格式)中完成,该文件仅当激活了对应的profile(`test`)才会被加载。 ```yaml app: id: "your-app-id-for-tests" apollo: meta: http://localhost:8080 # 假设这是本地部署的meta server URL spring: profiles: active: test ``` 上述YAML片段展示了如何针对测试目的定制Apollo的行为方式[^4]。 #### 编写基于JUnit/Jupiter框架的具体测试案例 一旦完成了前面提到的基础准备工作之后,就可以像平常一样创建具体的测试方法了。下面给出了一段简单的例子用来验证某个依赖注入组件是否按照预期接收到由Apollo提供的参数值。 ```java import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; class SomeServiceTest { @Autowired private SomeService someService; @Test void shouldReturnExpectedValueFromApolloConfig() throws Exception { String expectedValue = "value-from-apollo"; assertEquals(expectedValue, someService.getConfiguredProperty()); } } ``` 这段代码假设`SomeService`内部有一个名为`getConfiguredProperty()`的方法返回了一个字符串形式的应用程序配置项,而这个配置项是由Apollo动态下发给各个节点的[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值