3-1.加载测试专用属性
约 498 字大约 2 分钟
2025-06-24
在软件测试过程中,经常需要模拟线上环境或特殊情况。直接修改源码配置文件(如 application.yml)进行测试既繁琐又容易出错。为了解决这个问题,Spring Boot 提供了在测试环境中创建临时属性来覆盖源码属性的功能,从而保证测试用例的独立性。
1. 临时属性
通过在 @SpringBootTest 注解中添加 properties 属性,可以为当前测试用例添加临时属性配置。这些临时属性会覆盖源码配置文件中对应的属性值,方便进行特定场景的测试。
// properties 属性可以为当前测试用例添加临时的属性配置
@SpringBootTest(properties = {"test.prop=testValue1"})
public class PropertiesAndArgsTest {
@Value("${test.prop}")
private String msg;
@Test
void testProperties(){
System.out.println(msg);
}
}上述代码展示了如何使用 @SpringBootTest 的 properties 属性设置临时属性 test.prop 的值为 testValue1。通过 @Value 注解,可以将该属性值注入到测试类的 msg 字段中,并在测试方法中进行验证。
2. 临时参数
除了使用 properties 属性,还可以通过 @SpringBootTest 的 args 属性来模拟命令行参数,用于测试运维人员提供的配置信息是否有效。
// args 属性可以为当前测试用例添加临时的命令行参数
@SpringBootTest(args={"--test.prop=testValue2"})
public class PropertiesAndArgsTest {
@Value("${test.prop}")
private String msg;
@Test
void testProperties(){
System.out.println(msg);
}
}上述代码展示了如何使用 @SpringBootTest 的 args 属性模拟命令行参数 --test.prop=testValue2。同样地,通过 @Value 注解可以将该参数的值注入到测试类的 msg 字段中。
3. properties 和 args 共存时的优先级
当 properties 和 args 属性同时存在时,命令行参数(args)的优先级高于配置属性(properties)。这是因为在 Spring Boot 的属性加载优先级顺序中,命令行参数的优先级高于配置文件中的属性。