java - 在 Spring Boot 测试中正确使用 TestPropertyValues

标签 java spring-boot spring-boot-test

我遇到了 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 的属性注入(inject)(通过 @Value)。换句话说,我有一个这样的构造函数:

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

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

我知道我可以使用 @SpringBootTestproperties 参数,它会在创建 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)。如果您搜索代码库,您会发现许多其他通常使用方式的示例。

关于java - 在 Spring Boot 测试中正确使用 TestPropertyValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718995/

相关文章:

java - bundle -NativeCode : header in MANIFEST file give "Error: An unexpected error occurred while trying to open file pr.jar"

java - 从 application.properties Spring Boot 中读取值

java - 在 MongoDB Java 驱动程序中聚合时解析数据类型

spring-boot - 如何在 Spring Boot 的 JPA 存储库中编写查询?

java - 访问Heroku端点-Spring Boot App 503服务不可用

java - 访问 JSON 对象中的值

java - 在 Spring Boot 应用程序中使用 Spring Data JDBC

spring-boot - 如何在不运行tomcat的情况下运行spring boot test?

java - Spring boot项目无法解析符号SpringockitoContextLoader

spring-data-jpa - 如何在使用 DataJpaTest 的 Spring Boot 2.0 测试中访问 H2 控制台