【问题标题】:spring boot not picking test properties when running test classesspring boot 在运行测试类时没有选择测试属性
【发布时间】:2021-06-19 06:46:10
【问题描述】:

我尝试了一个 spring boot 2.4.0 应用程序,编写了一些测试。这是我的测试课

@SpringBootTest
@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:application-test.properties")
public class SampleTest {
    @Test
    public void testMethod1() {
        //some logic
    }
}

我有这个结构

src/
  main/
    java/
      //// further packages
    resources/
      bootstrap.yml
  test/
    resources/
      application-test.properties

上面的代码选择 bootstrap.yml 因为它包含这个属性 spring.profiles.active=${PROFILE} 顺便说一句,这个应用程序正在使用 spring-cloud-config

它给出了这个错误

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'PROFILE' in value "${PROFILE}"

为什么 spring-boot 没有提取我的测试属性文件?它始终优先于 bootstrap.yml 文件。请帮忙

【问题讨论】:

  • 移除 TestPropertySource 和 EnableConfigurationProperties
  • 为测试属性尝试相同的名称和扩展名。我的意思是在src/test/resource 中将application-test.properties 更改为application.yml
  • @SimonMartinelli 试过 EnableConfigurationProperties,没用

标签: spring-boot spring-boot-test


【解决方案1】:

在@SimonMartineli 的帮助下,我自己解决了这个问题。 我的 spring-boot 2.4.0 项目使用 spring-cloud-config。因此有 bootstrap.yml。它有两个属性

spring.active.profiles=${PROFILE}
spring.cloud.config.uri=${CONFIG_SERVER_URI}

这些占位符是运行时环境变量提供的值。

现在,即使我在我的测试课程中提到@TestPropertySource(locations = "classpath:application-test.properties"),它似乎也不起作用。测试类仍然尝试加载 bootstrap.yml 拳头。它曾经在我从中迁移的 spring-boot 2.1.5 中工作。

为了解决这个问题,我在我的测试类中使用了这个注解。

@SpringBootTest(properties = {"spring.cloud.config.enabled=false", "spring.profiles.active=test"}) 
public class SampleTest {
    @Test
    public void testMethod1() {
        //some logic
    }
}

所以这基本上解决了 spring-cloud-config 寻找的另一个属性,即 spring.profiles.active 并且它有一个占位符。 希望这对面临类似问题的人有所帮助。

【讨论】:

    【解决方案2】:

    我复制了你的例子,如果我把它添加到测试类中它就可以工作

    @ActiveProfiles("test")
    @SpringBootTest
    class SampleTest {
    

    您不需要任何其他注释。

    【讨论】:

    • 并且您保留了相同的测试结构和主要属性?
    • 这仍然不起作用。我的项目中也有 spring-kafka-test 依赖项。这会以某种方式干扰吗?
    • 比较你的项目和我的项目:github.com/simasch/demo-profiles
    • 我在帖子中犯了一个错误。我的项目中有 bootstrap.yml 而不是 application.yml。现在一个奇怪的观察,如果我将名称从引导程序更改为应用程序,那么一切正常。测试类选择了src/test/resources/application-test.properties 文件!
    • 可以,因为 bootstrap.yaml 是给 Spring Cloud 的,会一直被捡起来
    猜你喜欢
    • 2015-10-19
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2017-01-25
    • 2023-03-31
    • 2021-06-10
    相关资源
    最近更新 更多