【问题标题】:Run gradle task with Spring Profiles (Integration tests)使用 Spring Profiles 运行 gradle 任务(集成测试)
【发布时间】:2017-10-30 14:48:03
【问题描述】:

需要使用 spring 配置文件通过 gradle 运行测试。

gradle clean build

我已添加任务:

task beforeTest() {
    doLast {
      System.setProperty("spring.profiles.active", "DEV")
    }
}

test.dependsOn beforeTest

而我的测试定义是:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("TestProfile")
public class SomeTest {

但是这种结构对我不起作用。

Gradle 运行测试。

【问题讨论】:

    标签: java spring gradle profiling spring-profiles


    【解决方案1】:

    我认为您想在运行时/测试 JVM 中设置系统属性,但您在构建时 JVM(即 Gradle 守护程序)中错误地设置了系统属性。

    Test.systemProperty(String, Object)

    例如:

    test {
        systemProperty 'spring.profiles.active', 'DEV'
    }
    

    ... 以及关于您的尝试的另一个说明。请注意,任务具有 doFirstdoLast 方法,因此您不需要单独的任务来执行您正在尝试的操作。

    【讨论】:

    • 谢谢,但对我没有帮助
    • 注意这个属性需要在build.gradle文件中添加
    【解决方案2】:

    这对我有用:

    test {
        doFirst {
            systemProperty 'spring.profiles.active', 'ci'
        }
    }
    

    现在,当我执行 gradlew test 时,它会使用 ci 配置文件运行。

    【讨论】:

    • 您不应该在doFirst {...}it 的任务配置中执行此操作,这应该在配置阶段完成,而不是在执行阶段完成。见build phases
    【解决方案3】:

    想知道这是不是一个很晚的回复?但是我遇到了类似的情况。

    1. 在 springboot src/test/* 文件夹中使用@Profiles。
    2. @ActiveProfiles 实际上已激活(查看日志时),但在使用 gradle test 执行时不使用@Profile。但是,在执行 JUnit 测试时,@Profile 正在 Eclipse 编辑器中工作。

    所以最后我发现@Profile 需要在 src/main/* 文件夹中。 Gradle 测试似乎优先于 /src/main 而不是 /src/test。有了这个我的@Profile("test") 被转换成@Profile("!test")。构建的 gradle 中没有添加 spring.profiles.active。

    Negating profile

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 2014-07-11
      • 1970-01-01
      • 2016-06-12
      • 2013-08-06
      • 2017-08-17
      • 2020-07-22
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多