对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
使用动态属性源进行上下文配置
从 Spring Framework 5.2.5 开始,TestContext 框架通过@DynamicPropertySource
注解。 此注释可用于需要将具有动态值的属性添加到PropertySources
在Environment
对于ApplicationContext
加载为集成测试。
这 |
与@TestPropertySource
在类级别应用的注释,@DynamicPropertySource
必须应用到static
接受单个DynamicPropertyRegistry
参数,该参数是用于将名称-值对添加到Environment
. 值是动态的,通过 一个Supplier
仅在解析属性时调用。通常,方法引用用于提供值,如以下示例所示,该示例使用Testcontainers 项目来管理 Spring 之外的 Redis 容器ApplicationContext
. 托管 Redis 容器的 IP 地址和端口可用于测试中的组件ApplicationContext
通过redis.host
和redis.port
性能。 这些属性可以通过 Spring 的Environment
抽象或直接注入到 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
、系统属性源和应用程序属性源。