spring 具有动态属性的@TestPropertySource

pgky5nke  于 2023-04-28  发布在  Spring
关注(0)|答案(3)|浏览(328)

我正在使用@TestPropertySource覆盖应用程序。yml属性在我的Sping Boot 应用程序的集成测试中。

@TestPropertySource(properties = { "repository.file.path=src/test/resources/x" })

我想知道是否有某种方法可以使属性VALUE动态化。就像这样:

@TestPropertySource(properties = { "repository.file.path=PropertyValueProvider.class" })

感谢您的反馈。在我的例子中,属性值是系统特定的,应该在测试运行时生成。

cclgggtu

cclgggtu1#

@TestPropertySource仅提供用于配置PropertySource的 * 声明性 * 机制。Spring参考手册中的文档。
如果您需要将PropertySource添加到Environment的编程支持,您应该实现一个可以通过@ContextConfiguration(initializers = ...)注册的ApplicationContextInitializer。Spring参考手册中的文档。
致上,
Sam (Spring TestContext Framework的作者)

af7jpaap

af7jpaap2#

你也可以在Sping Boot 5中使用@DynamicPropertySource annotation。2.这使您能够以编程方式(动态地)设置属性值。
参见:https://github.com/spring-projects/spring-framework/issues/24540
将以下内容添加到您的集成测试类:

@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
  registry.add("my.property", () -> {
       // some logic to get your property dynamically
   });
}
lsmepo6l

lsmepo6l3#

感谢Sam Brannen's answer
下面是示例代码:

@ContextConfiguration(classes = { MyConfiguration.class }, initializers = { MyInitializer.class })
public class MyContextConfiguration {
    public static class MyInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            String userNameLower = System.getProperty("user.name").toLowerCase();
            Map<String, Object> dynamicProperties = Map.of("user.name.lower", userNameLower);
            MapPropertySource propertySource = new MapPropertySource("dynamic", dynamicProperties);
            applicationContext.getEnvironment().getPropertySources().addLast(propertySource);
        }
    }

    @Configuration
    @PropertySource("classpath:my-static.properties") // properties in this file can reference ${user.name.lower}
    public static class MyConfiguration {
        @Bean
        public MyBean myBean(@Value("${user.name.lower}") String userNameLower) {
            return new MyBean(userNameLower);
        }
    }
}

相关问题