【问题标题】:@TestPropertySource Class Could not resolve placeholder@TestPropertySource 类无法解析占位符
【发布时间】:2020-07-11 20:48:13
【问题描述】:

我正在使用具有 @PropertySource 注释的类 Propiedades 创建一个 TestClass

@Component
@PropertySource("file:${services.properties}test-app/.properties")
public class Propiedades {

    @Value("${db.name}")
    public String dbName;

    @Value("${db.jndi}")
    public String dbJNDI;

    @Value("${db.owner}")
    public String dbOwner;

}

如您所见,我正在从相对于部署应用程序的服务器的外部位置加载.properties 文件。 services.properties 是服务器的 env 变量,它具有到特定文件夹的路由。

这是我的测试课

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = Propiedades.class)
@TestPropertySource(locations = "/application-test.properties")
public class IncidenciaServicioServiceImplTest {

    @Autowired
    Propiedades propiedades;
    
    @Test
    public void isPropertySetup() {
        String output = propiedades.dbName;
        
        Assert.assertEquals("testDb", output);
    }
    
}

运行测试时出现以下错误。

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [Propiedades]; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'services.properties' in value "file:${services.properties}test-app/.properties"

为什么它试图从那个路径加载属性?,它不应该从src/test/resources/application-test.properties读取吗?

【问题讨论】:

    标签: java spring-boot unit-testing properties-file


    【解决方案1】:

    据我所知,Spring 不像您期望的那样工作。它总是首先尝试加载@PropertySource 中指定的属性,然后用@TestPropertySource 注释提供的值覆盖它们。

    因此,解决您的问题的一种方法是使用ignoreResourceNotFound 标志作为@PropertySource 注释:

    @PropertySource("file:${services.properties}test-app/.properties", ignoreResourceNotFound = true)
    public class Propiedades {
       // ... your properties
    }
    

    在这种情况下,Spring 将忽略它无法找到@PropertySource 指定的属性这一事实,并继续使用来自@TestPropertySource 的值

    或者,您需要在测试运行时为您的 ${services.properties} 环境变量提供值,以便解析到属性文件的正确路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2017-11-30
      • 1970-01-01
      • 2016-07-24
      • 2018-02-20
      相关资源
      最近更新 更多