junit 5 通过 @dynamicpropertysource 注解实现运行时配置注入,核心做法是在测试类中定义一个静态方法并加上该注解,在方法内部使用 registrycallback 对象调用 register() 方法将动态值绑定到指定的属性键。这样在测试执行期间,所有依赖配置的组件都能获取到这些临时生成的值,而无需修改全局配置文件。

如何向 Spring Boot 应用上下文注册动态属性?
在 Spring Boot 集成测试中,可以通过 TestPropertyValues.of() 辅助类将动态生成的值转换为属性源,并利用 ApplicationContextInitializer 将其注入到测试上下文中。具体做法是创建一个静态的 @DynamicPropertySource 方法,在其中构建包含随机端口或临时路径的属性集合并注册。这样做能确保 @SpringBootTest 启动的应用程序能够读取到这些非硬编码的配置项。

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.ContextConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(DynamicPropertyExtension.class)
@ContextConfiguration(initializers = DynamicPropertyInitializer.class)
class SpringBootDynamicConfigTest {
@Autowired
private ConfigurableApplicationContext context;
@Test
void testDynamicPropertyInSpring() {
String value = context.getEnvironment().getProperty("dynamic.test.key");
assertThat(value).isEqualTo("runtime-generated-value");
}
}
// 辅助类用于初始化上下文
class DynamicPropertyInitializer implements ApplicationContextInitializer<configurableapplicationcontext> {
@Override
public void initialize(ConfigurableApplicationContext context) {
TestPropertyValues.of("dynamic.test.key=runtime-generated-value")
.applyTo(context);
}
}</configurableapplicationcontext>
如何为第三方库或自定义 Bean 提供动态配置?
对于不直接依赖 Spring 环境的普通 JUnit 测试,或者需要模拟第三方客户端配置的场景,可以直接在 @DynamicPropertySource 方法中手动设置系统属性或环境变量。通过 registry.register() 可以指定具体的键名和对应的生成逻辑(如 UUID 或随机数)。这种方式适用于验证那些从 System.getProperty() 或环境变量读取配置的代码片段。

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.junit.jupiter.api.Assertions;
@ExtendWith(DynamicPropertyExtension.class)
class GenericDynamicConfigTest {
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
// 注册一个动态生成的 API Key
registry.add("api.key", () -> "generated-key-" + System.currentTimeMillis());
// 注册一个动态端口
registry.add("server.port", () -> String.valueOf(8080 + (int)(Math.random() * 1000)));
}
@Test
void testThirdPartyLibConfig() {
String apiKey = System.getProperty("api.key");
Assertions.assertNotNull(apiKey);
Assertions.assertTrue(apiKey.startsWith("generated-key-"));
}
}
动态属性在测试生命周期中的生效时机是什么?
动态注册的属性在测试方法执行前就已经被加载到测试环境的属性源链中。这意味着在测试类的构造函数、@BeforeEach 方法以及被测对象的初始化阶段,这些值都是可用的。如果尝试在 @DynamicPropertySource 方法之外去读取这些属性,可能会因为属性源尚未完全初始化而获取不到预期结果,因此必须确保读取操作发生在测试执行流程的正常阶段。











