|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
Context Configuration with Dynamic Property Sources
自Spring Framework 5.2.5起,TestContext框架通过动态属性支持@DynamicPropertySource注解。此注解可用于需要向加载的ApplicationContext中的Environment添加具有动态值的属性的集成测试。
|
The |
与应用于类级别的 @TestPropertySource
注解不同,@DynamicPropertySource 必须应用于接受单个 static 参数的 DynamicPropertyRegistry 方法,该参数用于向 Environment 添加 名称-值 对。值是动态的,并通过 Supplier 提供,该方法仅在解析属性时调用。通常,方法引用用于提供值,如以下示例所示,该示例使用 Testcontainers 项目在 Spring ApplicationContext 外管理 Redis 容器。Redis 容器的 IP 地址和端口通过 ApplicationContext 和 redis.host 属性提供给组件。这些属性可以通过 Spring 的 redis.port 抽象访问或直接注入到 Spring 管理的组件中——例如,分别通过 @Value("${redis.host}") 和 @Value("${redis.port}")。
|
如果您在基类中使用 |
-
Java
-
Kotlin
@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {
@Container
static GenericContainer redis =
new GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379);
@DynamicPropertySource
static void redisProperties(DynamicPropertyRegistry registry) {
registry.add("redis.host", redis::getHost);
registry.add("redis.port", redis::getFirstMappedPort);
}
// tests ...
}
@SpringJUnitConfig(/* ... */)
@Testcontainers
class ExampleIntegrationTests {
companion object {
@Container
@JvmStatic
val redis: GenericContainer =
GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379)
@DynamicPropertySource
@JvmStatic
fun redisProperties(registry: DynamicPropertyRegistry) {
registry.add("redis.host", redis::getHost)
registry.add("redis.port", redis::getFirstMappedPort)
}
}
// tests ...
}
优先级
动态属性的优先级高于从@TestPropertySource、操作系统环境、Java系统属性或应用程序通过使用@PropertySource或编程方式添加的属性源加载的属性。因此,动态属性可以用来有选择地覆盖通过@TestPropertySource、系统属性源和应用程序属性源加载的属性。