运行测试类时,spring boot 不选择测试属性

问题描述

我尝试了一个 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 文件。请帮忙

解决方法

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

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

您不需要任何其他注释。

,

我在@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 并且它有一个占位符。 希望这对面临类似问题的人有所帮助。