【问题标题】:@TestPropertySource with dynamic properties@TestPropertySource 具有动态属性
【发布时间】:2016-02-24 15:56:05
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: spring spring-mvc spring-boot spring-test


    【解决方案1】:

    @TestPropertySource 仅提供声明性 机制来配置PropertySources。 Documentation 在 Spring 参考手册中。

    如果您需要将PropertySource 添加到Environment 的编程支持,您应该实现一个ApplicationContextInitializer,它可以通过@ContextConfiguration(initializers = ...) 注册。 Documentation 在 Spring 参考手册中。

    问候,

    Sam (Spring TestContext 框架的作者)

    【讨论】:

    • 我找到了this example 来展示它是如何在实践中完成的。
    • @barfuin - 这看起来正是我需要的......除了我使用的是 Boot v1.5 并且该示例使用了 2.0 中引入的功能(TestPropertyValues)。不要以为有人会有其他例子吗?
    • 在 Spring Boot 1.5.x 中,您可以使用 @SpringBootTest 的 properties 属性:docs.spring.io/spring-boot/docs/1.5.21.BUILD-SNAPSHOT/api/org/…
    【解决方案2】:

    感谢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);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您也可以使用 Spring Boot 5.2 中的 @DynamicPropertySource 注解来做到这一点

      见: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
         });
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-27
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 2017-01-22
        • 2021-09-13
        • 2011-12-09
        • 2011-11-16
        相关资源
        最近更新 更多