Appropriate usage of TestPropertyValues in Spring Boot Tests

♀尐吖头ヾ 提交于 2020-06-26 04:52:34

问题


I came across TestPropertyValues, which is briefly mentioned in the Spring Boot docs here: 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

It's also mentioned in the Migration Guide here: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#environmenttestutils

Both examples show an environment variable to apply the properties to, but there's no other documentation that I could find.

In my tests the property setting comes too late to affect the property injection (via @Value) for a Spring Bean. In other words, I have a constructor like this:

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

Since the above constructor is called before the test code has a chance to run, there's no way change the property via TestPropertyValues in the test before it's used in the constructor.

I understand that I can use the properties parameter for @SpringBootTest, which updates the environment before beans get created, so what's the appropriate usage of TestPropertyValues?


回答1:


TestPropertyValues isn't really designed with @SpringBootTest in mind. It's much more useful when you are writing tests that manually create an ApplicationContext. If you really want to use it with @SpringBootTest, it should be possible to via an ApplicationContextInitializer. Something like this:

@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's own test make use of TestPropertyValues quite a bit. For example, applyToSystemProperties is very useful when you need to set system properties and you don't want them to be accidentally left after the test finishes (See EnvironmentEndpointTests for an example of that). If you search the codebase you'll find quite a few other examples of the kinds of ways it usually gets used.



来源:https://stackoverflow.com/questions/54718995/appropriate-usage-of-testpropertyvalues-in-spring-boot-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!