如何在 Spring 引导集成测试中覆盖 application.properties?

How to override application.properties in Spring Boot integration test?

我已经设置好 integration tests with Gradle and want to use Spring's "property inheritance"。但是 main 中的 application.properties 被完全替换了。

目录结构:

src/
  intTest/
    kotlin/my/package/
      SomethingTest.kt
    resources/
      application.properties
  main/
    kotlin/my/package/
      Something.kt
    resources/
      application.properties

原因可能是我在 intTest main 中使用 application.properties(具有相同的文件名) ] 目录。但是,如果我使用的是一个配置文件,我们称它为 "intTest" 和一个名为 application-intTest.properties 的文件,它也不起作用。配置文件特定文件根本没有被拾取。

Gradle 配置:

sourceSets {
    intTest {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}

configurations {
    intTestImplementation.extendsFrom testImplementation
    intTestRuntimeOnly.extendsFrom runtimeOnly
}

task integrationTest(type: Test) {
    description = 'Runs integration tests.'
    group = 'verification'
    useJUnitPlatform()
    systemProperty 'spring.profiles.active', 'intTest'
    testClassesDirs = sourceSets.intTest.output.classesDirs
    classpath = sourceSets.intTest.runtimeClasspath
    shouldRunAfter test
}

check.dependsOn integrationTest

测试 class(基于 JUnit 5)注释为:

@ExtendWith(SpringExtension::class)
@ComponentScan
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)

如果我将 @TestPropertySource 添加到我的测试 class 属性文件至少会被提取:

@TestPropertySource(locations= ["classpath:application-intTest.properties"])

但是 "properties inheritance" 也不起作用。所以它基本上与使用 application.properties 相同(没有配置文件部分),它覆盖了 main.

的所有属性

@Profile("intTest") 添加到我的测试中并不能解决问题。这同样适用于 @ActiveProfiles("intTest").

如何在我的集成测试设置中使用 "properties inheritance"?

原来问题不是我的 Gradle 配置而是我的 IntelliJ 配置。必须在 运行 配置中设置活动配置文件——即集成测试文件夹中的每个 运行 配置。这可以通过用 @ActiveProfiles("intTest").

注释集成测试 类 来解决