【问题标题】:How to override application.properties in Spring Boot integration test?如何在 Spring Boot 集成测试中覆盖 application.properties?
【发布时间】:2019-08-20 05:22:11
【问题描述】:

我已设置integration tests with Gradle 并想使用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 中使用application.properties(具有相同的文件名)main 目录中。但是,如果我使用的是配置文件,我们称之为“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

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

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

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

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

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

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

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

【问题讨论】:

  • 如果您将测试属性文件命名为 application.properties,那么它将覆盖 application.properties 文件,因为您只有一个类路径。但是使用配置文件对我有用。

标签: java spring spring-boot gradle integration-testing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2018-11-09
    • 2019-10-31
    • 2019-08-17
    • 2014-06-27
    • 2017-03-30
    • 2017-06-18
    • 2015-05-18
    相关资源
    最近更新 更多