在Spring Boot Tests中适当使用TestPropertyValues

问题描述 投票:0回答:1

我遇到了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更改属性。

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

java spring-boot spring-boot-test
1个回答
2
投票

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的示例)。如果你搜索代码库,你会发现很多其他通常使用的方法的例子。

© www.soinside.com 2019 - 2024. All rights reserved.