在 Spring 启动测试中正确使用 TestPropertyValues

Appropriate usage of TestPropertyValues in Spring Boot Tests

我遇到了 TestPropertyValues,这里的 Spring 引导文档中简要提到了它: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 变量来应用属性,但没有我能找到的其他文档。

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

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

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

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

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