【问题标题】:How to make externalized properties file available to spring boot integration tests?如何使外部属性文件可用于 Spring Boot 集成测试?
【发布时间】:2018-08-03 21:08:57
【问题描述】:

我正在使用 Spring Boot 开发应用程序。我在文件系统上有一个外部化的属性文件。它的位置存储在一个环境变量中,如下所示--

export props=file://Path-to-file-on-filesystem/file.properties

此文件中的属性加载到类路径中,并可供应用程序使用,如下所示--

List<String> argList = new ArrayList<>();
String properties = System.getenv().get("props");

try (InputStream is = BinaryFileReaderImpl.getInstance().getResourceAsStream(properties)) {
    if (is != null) {
        Properties props = new Properties();
        props.load(is);
        for(String prop : props.stringPropertyNames()) {
            argList.add("--" + prop + "=" + props.getProperty(prop));
        }
    }
} catch(Exception e) {
    //exception handling
}

这个 argList 被传递给SpringBootApplication,当它像下面这样开始时--

SpringApplication.run(MainApplication.class, argList);

我可以使用${prop.name}访问所有属性

但是,当我运行 JUnit 集成测试时,我无权访问这些属性。我所有的数据库属性都在这个外部属性文件中。我不想将此文件保留在应用程序中的任何位置,例如。 src/main/resources

有什么方法可以在 spring 的测试上下文中加载这些属性?

【问题讨论】:

  • 您是否在测试中尝试过 @PropertySource 注释?
  • 是的,我已经尝试过@PropertySource({"file:${props}"),正如提到的here。它在 Windows 上不起作用。没有在 Linux 上尝试过。

标签: spring spring-boot junit properties properties-file


【解决方案1】:

我终于可以在 linux 机器上使用@PropertySource 读取外部化的属性文件了。但无法让它在 Windows 实例上运行。

所做的更改如下-

export props=/path-to-file

请注意,file:// 和实际文件名已从环境变量中删除。

@Configuration
@PropertySource({"file:${props}/file-test.properties", "classpath:some_other_file.properties"}) 
public class TestConfiguration {

}

将此配置类保存在各个项目的 src/test/java 文件夹中。感谢Joe Chiavaroli 的上述评论。

【讨论】:

  • 这也适用于 Windows。要使windows系统变量生效,你需要重启你的IDE/CMD。
  • 我会使用以下注释@TestConfiguration@TestPropertySource
猜你喜欢
  • 2017-07-12
  • 2021-08-04
  • 1970-01-01
  • 2020-07-30
  • 2018-08-01
  • 2018-02-21
  • 2015-06-26
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多