【问题标题】:Appropriate usage of TestPropertyValues in Spring Boot Tests在 Spring Boot Tests 中正确使用 TestPropertyValues
【发布时间】:2019-02-19 11:50:37
【问题描述】:

我遇到了TestPropertyValues,这里的 Spring Boot 文档中简要提到了这一点:https://github.com/spring-projects/spring-boot/blob/2.1.x/spring-boot-project/spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc#testpropertyvalues

这里的迁移指南中也提到了这一点:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#environmenttestutils

两个示例都显示了一个 environment 变量来应用属性,但我找不到其他文档。

在我的测试中,属性设置来不及影响 Spring Bean 的属性注入(通过@Value)。换句话说,我有一个这样的构造函数:

  public PhoneNumberAuthorizer(@Value("${KNOWN_PHONE_NUMBER}") String knownRawPhoneNumber) {
    this.knownRawPhoneNumber = knownRawPhoneNumber;
  }

由于在测试代码有机会运行之前调用了上述构造函数,因此在构造函数中使用之前,无法通过测试中的TestPropertyValues更改属性。

我知道我可以为@SpringBootTest 使用properties 参数,它会在创建bean 之前更新环境,那么TestPropertyValues 的适当用法是什么?

【问题讨论】:

    标签: java spring-boot spring-boot-test


    【解决方案1】:

    TestPropertyValues 的设计并没有真正考虑到@SpringBootTest。当您编写手动创建ApplicationContext 的测试时,它会更有用。如果您真的想将它与@SpringBootTest 一起使用,应该可以通过ApplicationContextInitializer 使用。像这样的:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ContextConfiguration(initializers = PropertyTest.MyPropertyInitializer.class)
    public class PropertyTest {
    
        @Autowired
        private ApplicationContext context;
    
        @Test
        public void test() {
            assertThat(this.context.getEnvironment().getProperty("foo")).isEqualTo("bar");
        }
    
        static class MyPropertyInitializer
                implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    
            @Override
            public void initialize(ConfigurableApplicationContext applicationContext) {
                TestPropertyValues.of("foo=bar").applyTo(applicationContext);
            }
    
        }
    
    }
    

    Spring Boot 自己的测试大量使用了TestPropertyValues。例如,applyToSystemProperties 在您需要设置系统属性并且您不希望在测试完成后意外留下它们时非常有用(参见EnvironmentEndpointTests 的示例)。如果您搜索代码库,您会发现很多其他示例,说明它通常被使用的方式。

    【讨论】:

    • 这是一个很棒的例子!谢谢!正是我要找的……!如果用户正在寻找测试 Properties 类本身,请确保在 @ContextConfiguration 的参数列表中定义 classes = MyProperties.class...
    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 2019-08-01
    • 2017-07-23
    • 2018-12-30
    • 2017-08-25
    • 2020-03-30
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多