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

dea*_*mon 3 java spring integration-testing gradle spring-boot

我已经使用 Gradle设置了集成测试,并且想要使用Spring 的“属性继承”。但application.propertiesfrommain被完全替换了。

目录结构:

src/
  intTest/
    kotlin/my/package/
      SomethingTest.kt
    resources/
      application.properties
  main/
    kotlin/my/package/
      Something.kt
    resources/
      application.properties
Run Code Online (Sandbox Code Playgroud)

原因可能是我application.propertiesintTest 中使用(具有相同的文件名)main。但是,如果我使用配置文件(将其称为“intTest”)和名为 的文件application-intTest.properties,它也不起作用。根本没有拾取配置文件特定文件。

摇篮配置:

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
Run Code Online (Sandbox Code Playgroud)

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

@ExtendWith(SpringExtension::class)
@ComponentScan
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
Run Code Online (Sandbox Code Playgroud)

如果我添加@TestPropertySource到我的测试类中,至少会拾取属性文件:

@TestPropertySource(locations= ["classpath:application-intTest.properties"])
Run Code Online (Sandbox Code Playgroud)

但“属性继承”也不起作用。application.properties所以它基本上与使用(没有配置文件部分)相同,它覆盖了来自的所有属性main.

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

如何在我的集成测试设置中使用“属性继承”?

dea*_*mon 5

事实证明,问题不是我的 Gradle 配置,而是我的 IntelliJ 配置。活动配置文件必须在运行配置中设置——即针对集成测试文件夹中的每个运行配置。这可以通过用 注释集成测试类来解决@ActiveProfiles("intTest")