|
对于最新稳定版本,请使用Spring Framework 7.0.1! |
带有动态属性源的上下文配置
自 Spring Framework 5.2.5 起,TestContext 框架通过@DynamicPropertySource注解。该注释可用于
需要向 集合添加带有动态值的属性的积分测试地产来源在环境对于应用上下文为
积分测试。
|
这 |
与@TestPropertySource在类级层面应用的注释,@DynamicPropertySource必须应用
转给静态的接受单一动态属性注册论元,该参数为
用于向环境.值是动态的,通过以下方式提供
一个提供商只有在该属性被解决时才会被调用。通常,方法
引用用于提供值,如下例所示,该示例使用
Testcontainers 项目用于管理 Spring 之外的 Redis 容器应用上下文.管理 Redis 容器的 IP 地址和端口被创建
测试中的组件可用应用上下文通过redis.host和redis.port性能。这些房产可通过Spring's访问环境抽象或直接注入 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、系统属性源和应用属性源。