【发布时间】:2020-03-07 11:01:53
【问题描述】:
我有一个类注入了位于src/main/resources 目录中的application.yaml 属性。
我编写了一个测试来断言这些属性是否按预期注入。
测试工作正常,但它使用的是来自src/main/resources 的application.yaml 文件。
我希望它使用来自src/test/resources 的test-application.yaml 文件来使用一些虚假值。
我在 Stackoverflow 上遵循了许多指南并阅读了许多问题,但无法使任何这些方法发挥作用。也许是因为我混淆了不同解决方案的注释或其他什么。
现状
我使用的是spring管理系统提供的spring版本
id("io.spring.dependency-management") version "1.0.9.RELEASE"
编辑: 我还使用以下相关依赖项:
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-webflux")
属性文件src/main/resources/application.yaml:
controlroom:
ftpConnections:
foo-importer:
host: ftp.stage.company.com
port: 22
user: foo-ftp
password: password
bar-importer:
host: ftp.stage.company.com
port: 22
user: bar-ftp
password: password
这是属性配置持有者类:
@Configuration
@ConfigurationProperties(prefix = "controlroom")
class FtpConnectionsProvider(
) {
lateinit var ftpConnections: Map<String, Map<String, String>>
}
这是当前从main/resources/application.yaml注入属性的测试类:
@ExtendWith(SpringExtension::class)
@SpringBootTest
internal class FtpConnectionsProviderTest(
@Autowired
val ftpConnectionsProvider: FtpConnectionsProvider
) {
@Test
fun `should fill FtpConnectionsProvider with properties from yaml`() {
assertThat(ftpConnectionsProvider.ftpConnections["foo-importer"]).containsAllEntriesOf(
mapOf(
"host" to "ftp.stage.company.com",
"port" to "22",
"user" to "foo-ftp",
"password" to "password"
))
assertThat(ftpConnectionsProvider.ftpConnections["bar-importer"]).containsAllEntriesOf(
mapOf(
"host" to "ftp.stage.company.com",
"port" to "22",
"user" to "bar-ftp",
"password" to "password"
))
}
}
如何使用 test-application.yaml ?
现在我想知道如何给测试提供只使用src/test/resources/test-application.yaml 的指令。
第一次尝试
@ExtendWith(SpringExtension::class)
@SpringBootTest
@TestPropertySource("classpath:test-application.yaml")
internal class FtpConnectionsProviderTest
结果:忽略它并继续使用src/main/resources/application.yaml
第二次尝试
人们说@TestPropertySource 无法读取.yaml 文件,因此我添加了@ContextConfiguration 注释,因为这是建议的修复。
@ExtendWith(SpringExtension::class)
@SpringBootTest
@TestPropertySource("classpath:test-application.yaml")
@ContextConfiguration(initializers=[ConfigFileApplicationContextInitializer::class])
internal class FtpConnectionsProviderTest
结果:忽略它并继续使用src/main/kotlin/resources/application.yaml
似乎没有任何效果。我不明白为什么这很重要,为什么找到解决方案如此复杂
【问题讨论】:
-
你确定在你的类路径中有SnakeYaml吗?
-
@xerx593 是的。 imgur.com/a/dANSEdf
-
不,不,抱歉,图片不是证据:您向我/我们展示了
*.yaml文件...我/我们需要:在您的spring-boot[-...]-starter/snake-yamlpom.xml/build.gradle. -
@xerx593 请查看我对我使用的依赖项现状的编辑。我想再次提一下,.yaml 文件的注入确实有效,但我无法引用
src/test/kolin/resources目录中的那个 -
谢谢! :)(排除 1 个“副作用”)
标签: spring spring-boot kotlin yaml